home *** CD-ROM | disk | FTP | other *** search
/ PC Advisor 2010 April / PCA177.iso / ESSENTIALS / Firefox Setup.exe / nonlocalized / chrome / browser.jar / content / browser / browser.js < prev    next >
Encoding:
JavaScript  |  2009-07-15  |  302.7 KB  |  8,750 lines

  1. //@line 63 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  2.  
  3. let Ci = Components.interfaces;
  4. let Cu = Components.utils;
  5. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  6.  
  7. const nsIWebNavigation = Components.interfaces.nsIWebNavigation;
  8.  
  9. const MAX_HISTORY_MENU_ITEMS = 15;
  10.  
  11. // We use this once, for Clear Private Data
  12. const GLUE_CID = "@mozilla.org/browser/browserglue;1";
  13.  
  14. var gCharsetMenu = null;
  15. var gLastBrowserCharset = null;
  16. var gPrevCharset = null;
  17. var gProxyFavIcon = null;
  18. var gLastValidURLStr = "";
  19. var gProgressCollapseTimer = null;
  20. var appCore = null;
  21. var gSidebarCommand = "";
  22. var gInPrintPreviewMode = false;
  23. let gDownloadMgr = null;
  24.  
  25. // Global variable that holds the nsContextMenu instance.
  26. var gContextMenu = null;
  27.  
  28. var gChromeState = null; // chrome state before we went into print preview
  29.  
  30. var gAutoHideTabbarPrefListener = null;
  31. var gBookmarkAllTabsHandler = null;
  32.  
  33. //@line 97 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  34.  
  35. //@line 99 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  36. var gEditUIVisible = true;
  37. //@line 101 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  38.  
  39. [
  40.   ["gBrowser",            "content"],
  41.   ["gNavToolbox",         "navigator-toolbox"],
  42.   ["gURLBar",             "urlbar"],
  43.   ["gNavigatorBundle",    "bundle_browser"],
  44.   ["gProgressMeterPanel", "statusbar-progresspanel"],
  45.   ["gFindBar",            "FindToolbar"]
  46. ].forEach(function (elementGlobal) {
  47.   var [name, id] = elementGlobal;
  48.   window.__defineGetter__(name, function () {
  49.     var element = document.getElementById(id);
  50.     if (!element)
  51.       return null;
  52.     delete window[name];
  53.     return window[name] = element;
  54.   });
  55.   window.__defineSetter__(name, function (val) {
  56.     delete window[name];
  57.     return window[name] = val;
  58.   });
  59. });
  60.  
  61. __defineGetter__("gPrefService", function() {
  62.   delete this.gPrefService;
  63.   return this.gPrefService = Cc["@mozilla.org/preferences-service;1"].
  64.                              getService(Ci.nsIPrefBranch2);
  65. });
  66.  
  67. __defineGetter__("PluralForm", function() {
  68.   delete this.PluralForm;
  69.   var tmpScope = {};
  70.   Cu.import("resource://gre/modules/PluralForm.jsm", tmpScope);
  71.   return this.PluralForm = tmpScope.PluralForm;
  72. });
  73. __defineSetter__("PluralForm", function (val) {
  74.   delete this.PluralForm;
  75.   return this.PluralForm = val;
  76. });
  77.  
  78. let gInitialPages = [
  79.   "about:blank",
  80.   "about:privatebrowsing",
  81.   "about:sessionrestore"
  82. ];
  83.  
  84. /**
  85. * We can avoid adding multiple load event listeners and save some time by adding
  86. * one listener that calls all real handlers.
  87. */
  88. function pageShowEventHandlers(event) {
  89.   // Filter out events that are not about the document load we are interested in
  90.   if (event.originalTarget == content.document) {
  91.     charsetLoadListener(event);
  92.     XULBrowserWindow.asyncUpdateUI();
  93.   }
  94. }
  95.  
  96. /**
  97.  * Determine whether or not the content area is displaying a page with frames,
  98.  * and if so, toggle the display of the 'save frame as' menu item.
  99.  **/
  100. function getContentAreaFrameCount()
  101. {
  102.   var saveFrameItem = document.getElementById("menu_saveFrame");
  103.   if (!content || !content.frames.length || !isContentFrame(document.commandDispatcher.focusedWindow))
  104.     saveFrameItem.setAttribute("hidden", "true");
  105.   else
  106.     saveFrameItem.removeAttribute("hidden");
  107. }
  108.  
  109. function UpdateBackForwardCommands(aWebNavigation) {
  110.   var backBroadcaster = document.getElementById("Browser:Back");
  111.   var forwardBroadcaster = document.getElementById("Browser:Forward");
  112.  
  113.   // Avoid setting attributes on broadcasters if the value hasn't changed!
  114.   // Remember, guys, setting attributes on elements is expensive!  They
  115.   // get inherited into anonymous content, broadcast to other widgets, etc.!
  116.   // Don't do it if the value hasn't changed! - dwh
  117.  
  118.   var backDisabled = backBroadcaster.hasAttribute("disabled");
  119.   var forwardDisabled = forwardBroadcaster.hasAttribute("disabled");
  120.   if (backDisabled == aWebNavigation.canGoBack) {
  121.     if (backDisabled)
  122.       backBroadcaster.removeAttribute("disabled");
  123.     else
  124.       backBroadcaster.setAttribute("disabled", true);
  125.   }
  126.  
  127.   if (forwardDisabled == aWebNavigation.canGoForward) {
  128.     if (forwardDisabled)
  129.       forwardBroadcaster.removeAttribute("disabled");
  130.     else
  131.       forwardBroadcaster.setAttribute("disabled", true);
  132.   }
  133. }
  134.  
  135. //@line 284 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  136.  
  137. function BookmarkThisTab() {
  138.   PlacesCommandHook.bookmarkPage(gBrowser.mContextTab.linkedBrowser,
  139.                                  PlacesUtils.bookmarksMenuFolderId, true);
  140. }
  141.  
  142. const gSessionHistoryObserver = {
  143.   observe: function(subject, topic, data)
  144.   {
  145.     if (topic != "browser:purge-session-history")
  146.       return;
  147.  
  148.     var backCommand = document.getElementById("Browser:Back");
  149.     backCommand.setAttribute("disabled", "true");
  150.     var fwdCommand = document.getElementById("Browser:Forward");
  151.     fwdCommand.setAttribute("disabled", "true");
  152.  
  153.     if (gURLBar) {
  154.       // Clear undo history of the URL bar
  155.       gURLBar.editor.transactionManager.clear()
  156.     }
  157.   }
  158. };
  159.  
  160. /**
  161.  * Given a starting docshell and a URI to look up, find the docshell the URI
  162.  * is loaded in. 
  163.  * @param   aDocument
  164.  *          A document to find instead of using just a URI - this is more specific. 
  165.  * @param   aDocShell
  166.  *          The doc shell to start at
  167.  * @param   aSoughtURI
  168.  *          The URI that we're looking for
  169.  * @returns The doc shell that the sought URI is loaded in. Can be in 
  170.  *          subframes.
  171.  */
  172. function findChildShell(aDocument, aDocShell, aSoughtURI) {
  173.   aDocShell.QueryInterface(Components.interfaces.nsIWebNavigation);
  174.   aDocShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  175.   var doc = aDocShell.getInterface(Components.interfaces.nsIDOMDocument);
  176.   if ((aDocument && doc == aDocument) || 
  177.       (aSoughtURI && aSoughtURI.spec == aDocShell.currentURI.spec))
  178.     return aDocShell;
  179.  
  180.   var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode);
  181.   for (var i = 0; i < node.childCount; ++i) {
  182.     var docShell = node.getChildAt(i);
  183.     docShell = findChildShell(aDocument, docShell, aSoughtURI);
  184.     if (docShell)
  185.       return docShell;
  186.   }
  187.   return null;
  188. }
  189.  
  190. const gPopupBlockerObserver = {
  191.   _reportButton: null,
  192.   _kIPM: Components.interfaces.nsIPermissionManager,
  193.  
  194.   onUpdatePageReport: function (aEvent)
  195.   {
  196.     if (aEvent.originalTarget != gBrowser.selectedBrowser)
  197.       return;
  198.  
  199.     if (!this._reportButton)
  200.       this._reportButton = document.getElementById("page-report-button");
  201.  
  202.     if (!gBrowser.pageReport) {
  203.       // Hide the popup blocker statusbar button
  204.       this._reportButton.removeAttribute("blocked");
  205.  
  206.       return;
  207.     }
  208.  
  209.     this._reportButton.setAttribute("blocked", true);
  210.  
  211.     // Only show the notification again if we've not already shown it. Since
  212.     // notifications are per-browser, we don't need to worry about re-adding
  213.     // it.
  214.     if (!gBrowser.pageReport.reported) {
  215.       if (gPrefService.getBoolPref("privacy.popups.showBrowserMessage")) {
  216.         var bundle_browser = document.getElementById("bundle_browser");
  217.         var brandBundle = document.getElementById("bundle_brand");
  218.         var brandShortName = brandBundle.getString("brandShortName");
  219.         var message;
  220.         var popupCount = gBrowser.pageReport.length;
  221. //@line 370 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  222.         var popupButtonText = bundle_browser.getString("popupWarningButton");
  223.         var popupButtonAccesskey = bundle_browser.getString("popupWarningButton.accesskey");
  224. //@line 376 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  225.         if (popupCount > 1)
  226.           message = bundle_browser.getFormattedString("popupWarningMultiple", [brandShortName, popupCount]);
  227.         else
  228.           message = bundle_browser.getFormattedString("popupWarning", [brandShortName]);
  229.  
  230.         var notificationBox = gBrowser.getNotificationBox();
  231.         var notification = notificationBox.getNotificationWithValue("popup-blocked");
  232.         if (notification) {
  233.           notification.label = message;
  234.         }
  235.         else {
  236.           var buttons = [{
  237.             label: popupButtonText,
  238.             accessKey: popupButtonAccesskey,
  239.             popup: "blockedPopupOptions",
  240.             callback: null
  241.           }];
  242.  
  243.           const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  244.           notificationBox.appendNotification(message, "popup-blocked",
  245.                                              "chrome://browser/skin/Info.png",
  246.                                              priority, buttons);
  247.         }
  248.       }
  249.  
  250.       // Record the fact that we've reported this blocked popup, so we don't
  251.       // show it again.
  252.       gBrowser.pageReport.reported = true;
  253.     }
  254.   },
  255.  
  256.   toggleAllowPopupsForSite: function (aEvent)
  257.   {
  258.     var currentURI = gBrowser.selectedBrowser.webNavigation.currentURI;
  259.     var pm = Components.classes["@mozilla.org/permissionmanager;1"]
  260.                        .getService(this._kIPM);
  261.     var shouldBlock = aEvent.target.getAttribute("block") == "true";
  262.     var perm = shouldBlock ? this._kIPM.DENY_ACTION : this._kIPM.ALLOW_ACTION;
  263.     pm.add(currentURI, "popup", perm);
  264.  
  265.     gBrowser.getNotificationBox().removeCurrentNotification();
  266.   },
  267.  
  268.   fillPopupList: function (aEvent)
  269.   {
  270.     var bundle_browser = document.getElementById("bundle_browser");
  271.     // XXXben - rather than using |currentURI| here, which breaks down on multi-framed sites
  272.     //          we should really walk the pageReport and create a list of "allow for <host>"
  273.     //          menuitems for the common subset of hosts present in the report, this will
  274.     //          make us frame-safe.
  275.     //
  276.     // XXXjst - Note that when this is fixed to work with multi-framed sites,
  277.     //          also back out the fix for bug 343772 where
  278.     //          nsGlobalWindow::CheckOpenAllow() was changed to also
  279.     //          check if the top window's location is whitelisted.
  280.     var uri = gBrowser.selectedBrowser.webNavigation.currentURI;
  281.     var blockedPopupAllowSite = document.getElementById("blockedPopupAllowSite");
  282.     try {
  283.       blockedPopupAllowSite.removeAttribute("hidden");
  284.  
  285.       var pm = Components.classes["@mozilla.org/permissionmanager;1"]
  286.                         .getService(this._kIPM);
  287.       if (pm.testPermission(uri, "popup") == this._kIPM.ALLOW_ACTION) {
  288.         // Offer an item to block popups for this site, if a whitelist entry exists
  289.         // already for it.
  290.         var blockString = bundle_browser.getFormattedString("popupBlock", [uri.host]);
  291.         blockedPopupAllowSite.setAttribute("label", blockString);
  292.         blockedPopupAllowSite.setAttribute("block", "true");
  293.       }
  294.       else {
  295.         // Offer an item to allow popups for this site
  296.         var allowString = bundle_browser.getFormattedString("popupAllow", [uri.host]);
  297.         blockedPopupAllowSite.setAttribute("label", allowString);
  298.         blockedPopupAllowSite.removeAttribute("block");
  299.       }
  300.     }
  301.     catch (e) {
  302.       blockedPopupAllowSite.setAttribute("hidden", "true");
  303.     }
  304.  
  305.     if (gPrivateBrowsingUI.privateBrowsingEnabled)
  306.       blockedPopupAllowSite.setAttribute("disabled", "true");
  307.  
  308.     var item = aEvent.target.lastChild;
  309.     while (item && item.getAttribute("observes") != "blockedPopupsSeparator") {
  310.       var next = item.previousSibling;
  311.       item.parentNode.removeChild(item);
  312.       item = next;
  313.     }
  314.  
  315.     var foundUsablePopupURI = false;
  316.     var pageReport = gBrowser.pageReport;
  317.     if (pageReport) {
  318.       for (var i = 0; i < pageReport.length; ++i) {
  319.         var popupURIspec = pageReport[i].popupWindowURI.spec;
  320.  
  321.         // Sometimes the popup URI that we get back from the pageReport
  322.         // isn't useful (for instance, netscape.com's popup URI ends up
  323.         // being "http://www.netscape.com", which isn't really the URI of
  324.         // the popup they're trying to show).  This isn't going to be
  325.         // useful to the user, so we won't create a menu item for it.
  326.         if (popupURIspec == "" || popupURIspec == "about:blank" ||
  327.             popupURIspec == uri.spec)
  328.           continue;
  329.  
  330.         // Because of the short-circuit above, we may end up in a situation
  331.         // in which we don't have any usable popup addresses to show in
  332.         // the menu, and therefore we shouldn't show the separator.  However,
  333.         // since we got past the short-circuit, we must've found at least
  334.         // one usable popup URI and thus we'll turn on the separator later.
  335.         foundUsablePopupURI = true;
  336.  
  337.         var menuitem = document.createElement("menuitem");
  338.         var label = bundle_browser.getFormattedString("popupShowPopupPrefix",
  339.                                                       [popupURIspec]);
  340.         menuitem.setAttribute("label", label);
  341.         menuitem.setAttribute("popupWindowURI", popupURIspec);
  342.         menuitem.setAttribute("popupWindowFeatures", pageReport[i].popupWindowFeatures);
  343.         menuitem.setAttribute("popupWindowName", pageReport[i].popupWindowName);
  344.         menuitem.setAttribute("oncommand", "gPopupBlockerObserver.showBlockedPopup(event);");
  345.         menuitem.requestingWindow = pageReport[i].requestingWindow;
  346.         menuitem.requestingDocument = pageReport[i].requestingDocument;
  347.         aEvent.target.appendChild(menuitem);
  348.       }
  349.     }
  350.  
  351.     // Show or hide the separator, depending on whether we added any
  352.     // showable popup addresses to the menu.
  353.     var blockedPopupsSeparator =
  354.       document.getElementById("blockedPopupsSeparator");
  355.     if (foundUsablePopupURI)
  356.       blockedPopupsSeparator.removeAttribute("hidden");
  357.     else
  358.       blockedPopupsSeparator.setAttribute("hidden", true);
  359.  
  360.     var blockedPopupDontShowMessage = document.getElementById("blockedPopupDontShowMessage");
  361.     var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
  362.     blockedPopupDontShowMessage.setAttribute("checked", !showMessage);
  363.     if (aEvent.target.localName == "popup")
  364.       blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromMessage"));
  365.     else
  366.       blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromStatusbar"));
  367.   },
  368.  
  369.   showBlockedPopup: function (aEvent)
  370.   {
  371.     var target = aEvent.target;
  372.     var popupWindowURI = target.getAttribute("popupWindowURI");
  373.     var features = target.getAttribute("popupWindowFeatures");
  374.     var name = target.getAttribute("popupWindowName");
  375.  
  376.     var dwi = target.requestingWindow;
  377.  
  378.     // If we have a requesting window and the requesting document is
  379.     // still the current document, open the popup.
  380.     if (dwi && dwi.document == target.requestingDocument) {
  381.       dwi.open(popupWindowURI, name, features);
  382.     }
  383.   },
  384.  
  385.   editPopupSettings: function ()
  386.   {
  387.     var host = "";
  388.     try {
  389.       var uri = gBrowser.selectedBrowser.webNavigation.currentURI;
  390.       host = uri.host;
  391.     }
  392.     catch (e) { }
  393.  
  394.     var bundlePreferences = document.getElementById("bundle_preferences");
  395.     var params = { blockVisible   : false,
  396.                    sessionVisible : false,
  397.                    allowVisible   : true,
  398.                    prefilledHost  : host,
  399.                    permissionType : "popup",
  400.                    windowTitle    : bundlePreferences.getString("popuppermissionstitle"),
  401.                    introText      : bundlePreferences.getString("popuppermissionstext") };
  402.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  403.                         .getService(Components.interfaces.nsIWindowMediator);
  404.     var existingWindow = wm.getMostRecentWindow("Browser:Permissions");
  405.     if (existingWindow) {
  406.       existingWindow.initWithParams(params);
  407.       existingWindow.focus();
  408.     }
  409.     else
  410.       window.openDialog("chrome://browser/content/preferences/permissions.xul",
  411.                         "_blank", "resizable,dialog=no,centerscreen", params);
  412.   },
  413.  
  414.   dontShowMessage: function ()
  415.   {
  416.     var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
  417.     var firstTime = gPrefService.getBoolPref("privacy.popups.firstTime");
  418.  
  419.     // If the info message is showing at the top of the window, and the user has never
  420.     // hidden the message before, show an info box telling the user where the info
  421.     // will be displayed.
  422.     if (showMessage && firstTime)
  423.       this._displayPageReportFirstTime();
  424.  
  425.     gPrefService.setBoolPref("privacy.popups.showBrowserMessage", !showMessage);
  426.  
  427.     gBrowser.getNotificationBox().removeCurrentNotification();
  428.   },
  429.  
  430.   _displayPageReportFirstTime: function ()
  431.   {
  432.     window.openDialog("chrome://browser/content/pageReportFirstTime.xul", "_blank",
  433.                       "dependent");
  434.   }
  435. };
  436.  
  437. const gXPInstallObserver = {
  438.   _findChildShell: function (aDocShell, aSoughtShell)
  439.   {
  440.     if (aDocShell == aSoughtShell)
  441.       return aDocShell;
  442.  
  443.     var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode);
  444.     for (var i = 0; i < node.childCount; ++i) {
  445.       var docShell = node.getChildAt(i);
  446.       docShell = this._findChildShell(docShell, aSoughtShell);
  447.       if (docShell == aSoughtShell)
  448.         return docShell;
  449.     }
  450.     return null;
  451.   },
  452.  
  453.   _getBrowser: function (aDocShell)
  454.   {
  455.     for (var i = 0; i < gBrowser.browsers.length; ++i) {
  456.       var browser = gBrowser.getBrowserAtIndex(i);
  457.       if (this._findChildShell(browser.docShell, aDocShell))
  458.         return browser;
  459.     }
  460.     return null;
  461.   },
  462.  
  463.   observe: function (aSubject, aTopic, aData)
  464.   {
  465.     var brandBundle = document.getElementById("bundle_brand");
  466.     var browserBundle = document.getElementById("bundle_browser");
  467.     switch (aTopic) {
  468.     case "xpinstall-install-blocked":
  469.       var installInfo = aSubject.QueryInterface(Components.interfaces.nsIXPIInstallInfo);
  470.       var win = installInfo.originatingWindow;
  471.       var shell = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  472.                      .getInterface(Components.interfaces.nsIWebNavigation)
  473.                      .QueryInterface(Components.interfaces.nsIDocShell);
  474.       var browser = this._getBrowser(shell);
  475.       if (browser) {
  476.         var host = installInfo.originatingURI.host;
  477.         var brandShortName = brandBundle.getString("brandShortName");
  478.         var notificationName, messageString, buttons;
  479.         if (!gPrefService.getBoolPref("xpinstall.enabled")) {
  480.           notificationName = "xpinstall-disabled"
  481.           if (gPrefService.prefIsLocked("xpinstall.enabled")) {
  482.             messageString = browserBundle.getString("xpinstallDisabledMessageLocked");
  483.             buttons = [];
  484.           }
  485.           else {
  486.             messageString = browserBundle.getFormattedString("xpinstallDisabledMessage",
  487.                                                              [brandShortName, host]);
  488.  
  489.             buttons = [{
  490.               label: browserBundle.getString("xpinstallDisabledButton"),
  491.               accessKey: browserBundle.getString("xpinstallDisabledButton.accesskey"),
  492.               popup: null,
  493.               callback: function editPrefs() {
  494.                 gPrefService.setBoolPref("xpinstall.enabled", true);
  495.                 return false;
  496.               }
  497.             }];
  498.           }
  499.         }
  500.         else {
  501.           notificationName = "xpinstall"
  502.           messageString = browserBundle.getFormattedString("xpinstallPromptWarning",
  503.                                                            [brandShortName, host]);
  504.  
  505.           buttons = [{
  506.             label: browserBundle.getString("xpinstallPromptAllowButton"),
  507.             accessKey: browserBundle.getString("xpinstallPromptAllowButton.accesskey"),
  508.             popup: null,
  509.             callback: function() {
  510.               var mgr = Components.classes["@mozilla.org/xpinstall/install-manager;1"]
  511.                                   .createInstance(Components.interfaces.nsIXPInstallManager);
  512.               mgr.initManagerWithInstallInfo(installInfo);
  513.               return false;
  514.             }
  515.           }];
  516.         }
  517.  
  518.         var notificationBox = gBrowser.getNotificationBox(browser);
  519.         if (!notificationBox.getNotificationWithValue(notificationName)) {
  520.           const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  521.           const iconURL = "chrome://mozapps/skin/update/update.png";
  522.           notificationBox.appendNotification(messageString, notificationName,
  523.                                              iconURL, priority, buttons);
  524.         }
  525.       }
  526.       break;
  527.     }
  528.   }
  529. };
  530.  
  531. // Simple gestures support
  532. //
  533. // As per bug #412486, web content must not be allowed to receive any
  534. // simple gesture events.  Multi-touch gesture APIs are in their
  535. // infancy and we do NOT want to be forced into supporting an API that
  536. // will probably have to change in the future.  (The current Mac OS X
  537. // API is undocumented and was reverse-engineered.)  Until support is
  538. // implemented in the event dispatcher to keep these events as
  539. // chrome-only, we must listen for the simple gesture events during
  540. // the capturing phase and call stopPropagation on every event.
  541.  
  542. let gGestureSupport = {
  543.   /**
  544.    * Add or remove mouse gesture event listeners
  545.    *
  546.    * @param aAddListener
  547.    *        True to add/init listeners and false to remove/uninit
  548.    */
  549.   init: function GS_init(aAddListener) {
  550.     const gestureEvents = ["SwipeGesture",
  551.       "MagnifyGestureStart", "MagnifyGestureUpdate", "MagnifyGesture",
  552.       "RotateGestureStart", "RotateGestureUpdate", "RotateGesture",
  553.       "TapGesture", "PressTapGesture"];
  554.  
  555.     let addRemove = aAddListener ? window.addEventListener :
  556.       window.removeEventListener;
  557.  
  558.     for each (let event in gestureEvents)
  559.       addRemove("Moz" + event, this, true);
  560.   },
  561.  
  562.   /**
  563.    * Dispatch events based on the type of mouse gesture event. For now, make
  564.    * sure to stop propagation of every gesture event so that web content cannot
  565.    * receive gesture events.
  566.    *
  567.    * @param aEvent
  568.    *        The gesture event to handle
  569.    */
  570.   handleEvent: function GS_handleEvent(aEvent) {
  571.     aEvent.stopPropagation();
  572.  
  573.     // Create a preference object with some defaults
  574.     let def = function(aThreshold, aLatched)
  575.       ({ threshold: aThreshold, latched: !!aLatched });
  576.  
  577.     switch (aEvent.type) {
  578.       case "MozSwipeGesture":
  579.         aEvent.preventDefault();
  580.         return this.onSwipe(aEvent);
  581.       case "MozMagnifyGestureStart":
  582.         aEvent.preventDefault();
  583. //@line 735 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  584.         return this._setupGesture(aEvent, "pinch", def(25, 0), "out", "in");
  585. //@line 739 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  586.       case "MozRotateGestureStart":
  587.         aEvent.preventDefault();
  588.         return this._setupGesture(aEvent, "twist", def(25, 0), "right", "left");
  589.       case "MozMagnifyGestureUpdate":
  590.       case "MozRotateGestureUpdate":
  591.         aEvent.preventDefault();
  592.         return this._doUpdate(aEvent);
  593.       case "MozTapGesture":
  594.         aEvent.preventDefault();
  595.         return this._doAction(aEvent, ["tap"]);
  596.       case "MozPressTapGesture":
  597.       // Fall through to default behavior
  598.       return;
  599.     }
  600.   },
  601.  
  602.   /**
  603.    * Called at the start of "pinch" and "twist" gestures to setup all of the
  604.    * information needed to process the gesture
  605.    *
  606.    * @param aEvent
  607.    *        The continual motion start event to handle
  608.    * @param aGesture
  609.    *        Name of the gesture to handle
  610.    * @param aPref
  611.    *        Preference object with the names of preferences and defaults
  612.    * @param aInc
  613.    *        Command to trigger for increasing motion (without gesture name)
  614.    * @param aDec
  615.    *        Command to trigger for decreasing motion (without gesture name)
  616.    */
  617.   _setupGesture: function GS__setupGesture(aEvent, aGesture, aPref, aInc, aDec) {
  618.     // Try to load user-set values from preferences
  619.     for (let [pref, def] in Iterator(aPref))
  620.       aPref[pref] = this._getPref(aGesture + "." + pref, def);
  621.  
  622.     // Keep track of the total deltas and latching behavior
  623.     let offset = 0;
  624.     let latchDir = aEvent.delta > 0 ? 1 : -1;
  625.     let isLatched = false;
  626.  
  627.     // Create the update function here to capture closure state
  628.     this._doUpdate = function GS__doUpdate(aEvent) {
  629.       // Update the offset with new event data
  630.       offset += aEvent.delta;
  631.  
  632.       // Check if the cumulative deltas exceed the threshold
  633.       if (Math.abs(offset) > aPref["threshold"]) {
  634.         // Trigger the action if we don't care about latching; otherwise, make
  635.         // sure either we're not latched and going the same direction of the
  636.         // initial motion; or we're latched and going the opposite way
  637.         let sameDir = (latchDir ^ offset) >= 0;
  638.         if (!aPref["latched"] || (isLatched ^ sameDir)) {
  639.           this._doAction(aEvent, [aGesture, offset > 0 ? aInc : aDec]);
  640.  
  641.           // We must be getting latched or leaving it, so just toggle
  642.           isLatched = !isLatched;
  643.         }
  644.  
  645.         // Reset motion counter to prepare for more of the same gesture
  646.         offset = 0;
  647.       }
  648.     };
  649.  
  650.     // The start event also contains deltas, so handle an update right away
  651.     this._doUpdate(aEvent);
  652.   },
  653.  
  654.   /**
  655.    * Generator producing the powerset of the input array where the first result
  656.    * is the complete set and the last result (before StopIteration) is empty.
  657.    *
  658.    * @param aArray
  659.    *        Source array containing any number of elements
  660.    * @yield Array that is a subset of the input array from full set to empty
  661.    */
  662.   _power: function GS__power(aArray) {
  663.     // Create a bitmask based on the length of the array
  664.     let num = 1 << aArray.length;
  665.     while (--num >= 0)
  666.       // Only select array elements where the current bit is set
  667.       yield aArray.reduce(function(aPrev, aCurr, aIndex) {
  668.         if (num & 1 << aIndex)
  669.           aPrev.push(aCurr);
  670.         return aPrev;
  671.       }, []);
  672.   },
  673.  
  674.   /**
  675.    * Determine what action to do for the gesture based on which keys are
  676.    * pressed and which commands are set
  677.    *
  678.    * @param aEvent
  679.    *        The original gesture event to convert into a fake click event
  680.    * @param aGesture
  681.    *        Array of gesture name parts (to be joined by periods)
  682.    * @return Name of the command found for the event's keys and gesture. If no
  683.    *         command is found, no value is returned (undefined).
  684.    */
  685.   _doAction: function GS__doAction(aEvent, aGesture) {
  686.     // Create a fake event that pretends the gesture is a button click
  687.     let fakeEvent = { shiftKey: aEvent.shiftKey, ctrlKey: aEvent.ctrlKey,
  688.       metaKey: aEvent.metaKey, altKey: aEvent.altKey, button: 0 };
  689.  
  690.     // Create an array of pressed keys in a fixed order so that a command for
  691.     // "meta" is preferred over "ctrl" when both buttons are pressed (and a
  692.     // command for both don't exist)
  693.     let keyCombos = [];
  694.     const keys = ["shift", "alt", "ctrl", "meta"];
  695.     for each (let key in keys)
  696.       if (aEvent[key + "Key"])
  697.         keyCombos.push(key);
  698.  
  699.     try {
  700.       // Try each combination of key presses in decreasing order for commands
  701.       for (let subCombo in this._power(keyCombos)) {
  702.         // Convert a gesture and pressed keys into the corresponding command
  703.         // action where the preference has the gesture before "shift" before
  704.         // "alt" before "ctrl" before "meta" all separated by periods
  705.         let command = this._getPref(aGesture.concat(subCombo).join("."));
  706.  
  707.         // Do the command if we found one to do
  708.         if (command) {
  709.           let node = document.getElementById(command);
  710.           // Use the command element if it exists
  711.           if (node && node.hasAttribute("oncommand")) {
  712.             // XXX: Use node.oncommand(event) once bug 246720 is fixed
  713.             if (node.getAttribute("disabled") != "true")
  714.               new Function("event", node.getAttribute("oncommand")).
  715.                 call(node, fakeEvent);
  716.           }
  717.           // Otherwise it should be a "standard" command
  718.           else
  719.             goDoCommand(command);
  720.  
  721.           return command;
  722.         }
  723.       }
  724.     }
  725.     // The generator ran out of key combinations, so just do nothing
  726.     catch (e) {}
  727.   },
  728.  
  729.   /**
  730.    * Convert continual motion events into an action if it exceeds a threshold
  731.    * in a given direction. This function will be set by _setupGesture to
  732.    * capture state that needs to be shared across multiple gesture updates.
  733.    *
  734.    * @param aEvent
  735.    *        The continual motion update event to handle
  736.    */
  737.   _doUpdate: function(aEvent) {},
  738.  
  739.   /**
  740.    * Convert the swipe gesture into a browser action based on the direction
  741.    *
  742.    * @param aEvent
  743.    *        The swipe event to handle
  744.    */
  745.   onSwipe: function GS_onSwipe(aEvent) {
  746.     // Figure out which one (and only one) direction was triggered 
  747.     for each (let dir in ["UP", "RIGHT", "DOWN", "LEFT"])
  748.       if (aEvent.direction == aEvent["DIRECTION_" + dir])
  749.         return this._doAction(aEvent, ["swipe", dir.toLowerCase()]);
  750.   },
  751.  
  752.   /**
  753.    * Get a gesture preference or use a default if it doesn't exist
  754.    *
  755.    * @param aPref
  756.    *        Name of the preference to load under the gesture branch
  757.    * @param aDef
  758.    *        Default value if the preference doesn't exist
  759.    */
  760.   _getPref: function GS__getPref(aPref, aDef) {
  761.     // Preferences branch under which all gestures preferences are stored
  762.     const branch = "browser.gesture.";
  763.  
  764.     try {
  765.       // Determine what type of data to load based on default value's type
  766.       let type = typeof aDef;
  767.       let getFunc = "get" + (type == "boolean" ? "Bool" : 
  768.                              type == "number" ? "Int" : "Char") + "Pref";
  769.       return gPrefService[getFunc](branch + aPref);
  770.     }
  771.     catch (e) {
  772.       return aDef;
  773.     }
  774.   },
  775. };
  776.  
  777. function BrowserStartup() {
  778.   var uriToLoad = null;
  779.  
  780.   // window.arguments[0]: URI to load (string), or an nsISupportsArray of
  781.   //                      nsISupportsStrings to load, or a xul:tab of
  782.   //                      a tabbrowser, which will be replaced by this
  783.   //                      window (for this case, all other arguments are
  784.   //                      ignored).
  785.   //                 [1]: character set (string)
  786.   //                 [2]: referrer (nsIURI)
  787.   //                 [3]: postData (nsIInputStream)
  788.   //                 [4]: allowThirdPartyFixup (bool)
  789.   if ("arguments" in window && window.arguments[0])
  790.     uriToLoad = window.arguments[0];
  791.  
  792.   var isLoadingBlank = uriToLoad == "about:blank";
  793.   var mustLoadSidebar = false;
  794.  
  795.   prepareForStartup();
  796.  
  797. //@line 954 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  798.   if (uriToLoad && !isLoadingBlank) { 
  799.     if (uriToLoad instanceof Ci.nsISupportsArray) {
  800.       let count = uriToLoad.Count();
  801.       let specs = [];
  802.       for (let i = 0; i < count; i++) {
  803.         let urisstring = uriToLoad.GetElementAt(i).QueryInterface(Ci.nsISupportsString);
  804.         specs.push(urisstring.data);
  805.       }
  806.  
  807.       // This function throws for certain malformed URIs, so use exception handling
  808.       // so that we don't disrupt startup
  809.       try {
  810.         gBrowser.loadTabs(specs, false, true);
  811.       } catch (e) {}
  812.     }
  813.     else if (uriToLoad instanceof XULElement) {
  814.       // swap the given tab with the default about:blank tab and then close
  815.       // the original tab in the other window.
  816.  
  817.       // Stop the about:blank load
  818.       gBrowser.selectedBrowser.stop();
  819.       // make sure it has a docshell
  820.       gBrowser.selectedBrowser.docShell;
  821.  
  822.       gBrowser.swapBrowsersAndCloseOther(gBrowser.selectedTab, uriToLoad);
  823.     }
  824.     else if (window.arguments.length >= 3) {
  825.       loadURI(uriToLoad, window.arguments[2], window.arguments[3] || null,
  826.               window.arguments[4] || false);
  827.       content.focus();
  828.     }
  829.     // Note: loadOneOrMoreURIs *must not* be called if window.arguments.length >= 3.
  830.     // Such callers expect that window.arguments[0] is handled as a single URI.
  831.     else
  832.       loadOneOrMoreURIs(uriToLoad);
  833.   }
  834. //@line 991 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  835.  
  836.   if (window.opener && !window.opener.closed) {
  837.     let openerFindBar = window.opener.gFindBar;
  838.     if (openerFindBar && !openerFindBar.hidden &&
  839.         openerFindBar.findMode == gFindBar.FIND_NORMAL)
  840.       gFindBar.open();
  841.  
  842.     let openerSidebarBox = window.opener.document.getElementById("sidebar-box");
  843.     // If the opener had a sidebar, open the same sidebar in our window.
  844.     // The opener can be the hidden window too, if we're coming from the state
  845.     // where no windows are open, and the hidden window has no sidebar box.
  846.     if (openerSidebarBox && !openerSidebarBox.hidden) {
  847.       let sidebarBox = document.getElementById("sidebar-box");
  848.       let sidebarTitle = document.getElementById("sidebar-title");
  849.       sidebarTitle.setAttribute("value", window.opener.document.getElementById("sidebar-title").getAttribute("value"));
  850.       sidebarBox.setAttribute("width", openerSidebarBox.boxObject.width);
  851.       let sidebarCmd = openerSidebarBox.getAttribute("sidebarcommand");
  852.       sidebarBox.setAttribute("sidebarcommand", sidebarCmd);
  853.       // Note: we're setting 'src' on sidebarBox, which is a <vbox>, not on the
  854.       // <browser id="sidebar">. This lets us delay the actual load until
  855.       // delayedStartup().
  856.       sidebarBox.setAttribute("src", window.opener.document.getElementById("sidebar").getAttribute("src"));
  857.       mustLoadSidebar = true;
  858.  
  859.       sidebarBox.hidden = false;
  860.       document.getElementById("sidebar-splitter").hidden = false;
  861.       document.getElementById(sidebarCmd).setAttribute("checked", "true");
  862.     }
  863.   }
  864.   else {
  865.     let box = document.getElementById("sidebar-box");
  866.     if (box.hasAttribute("sidebarcommand")) {
  867.       let commandID = box.getAttribute("sidebarcommand");
  868.       if (commandID) {
  869.         let command = document.getElementById(commandID);
  870.         if (command) {
  871.           mustLoadSidebar = true;
  872.           box.hidden = false;
  873.           document.getElementById("sidebar-splitter").hidden = false;
  874.           command.setAttribute("checked", "true");
  875.         }
  876.         else {
  877.           // Remove the |sidebarcommand| attribute, because the element it 
  878.           // refers to no longer exists, so we should assume this sidebar
  879.           // panel has been uninstalled. (249883)
  880.           box.removeAttribute("sidebarcommand");
  881.         }
  882.       }
  883.     }
  884.   }
  885.  
  886.   // Certain kinds of automigration rely on this notification to complete their
  887.   // tasks BEFORE the browser window is shown.
  888.   Cc["@mozilla.org/observer-service;1"]
  889.     .getService(Ci.nsIObserverService)
  890.     .notifyObservers(null, "browser-window-before-show", "");
  891.  
  892.   // Set a sane starting width/height for all resolutions on new profiles.
  893.   if (!document.documentElement.hasAttribute("width")) {
  894.     let defaultWidth = 994;
  895.     let defaultHeight;
  896.     if (screen.availHeight <= 600) {
  897.       document.documentElement.setAttribute("sizemode", "maximized");
  898.       defaultWidth = 610;
  899.       defaultHeight = 450;
  900.     }
  901.     else {
  902.       // Create a narrower window for large or wide-aspect displays, to suggest
  903.       // side-by-side page view.
  904.       if (screen.availWidth >= 1600)
  905.         defaultWidth = (screen.availWidth / 2) - 20;
  906.       defaultHeight = screen.availHeight - 10;
  907. //@line 1068 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  908.     }
  909.     document.documentElement.setAttribute("width", defaultWidth);
  910.     document.documentElement.setAttribute("height", defaultHeight);
  911.   }
  912.  
  913.   if (gURLBar && document.documentElement.getAttribute("chromehidden").indexOf("toolbar") != -1) {
  914.     gURLBar.setAttribute("readonly", "true");
  915.     gURLBar.setAttribute("enablehistory", "false");
  916.   }
  917.  
  918.   setTimeout(delayedStartup, 0, isLoadingBlank, mustLoadSidebar);
  919. }
  920.  
  921. function HandleAppCommandEvent(evt) {
  922.   evt.stopPropagation();
  923.   switch (evt.command) {
  924.   case "Back":
  925.     BrowserBack();
  926.     break;
  927.   case "Forward":
  928.     BrowserForward();
  929.     break;
  930.   case "Reload":
  931.     BrowserReloadSkipCache();
  932.     break;
  933.   case "Stop":
  934.     BrowserStop();
  935.     break;
  936.   case "Search":
  937.     BrowserSearch.webSearch();
  938.     break;
  939.   case "Bookmarks":
  940.     toggleSidebar('viewBookmarksSidebar');
  941.     break;
  942.   case "Home":
  943.     BrowserHome();
  944.     break;
  945.   default:
  946.     break;
  947.   }
  948. }
  949.  
  950. function prepareForStartup() {
  951.   gBrowser.addEventListener("DOMUpdatePageReport", gPopupBlockerObserver.onUpdatePageReport, false);
  952.   // Note: we need to listen to untrusted events, because the pluginfinder XBL
  953.   // binding can't fire trusted ones (runs with page privileges).
  954.   gBrowser.addEventListener("PluginNotFound", gMissingPluginInstaller.newMissingPlugin, true, true);
  955.   gBrowser.addEventListener("PluginBlocklisted", gMissingPluginInstaller.newMissingPlugin, true, true);
  956.   gBrowser.addEventListener("PluginDisabled", gMissingPluginInstaller.newDisabledPlugin, true, true);
  957.   gBrowser.addEventListener("NewPluginInstalled", gMissingPluginInstaller.refreshBrowser, false);
  958.   gBrowser.addEventListener("NewTab", BrowserOpenTab, false);
  959.   window.addEventListener("AppCommand", HandleAppCommandEvent, true);
  960.  
  961.   var webNavigation;
  962.   try {
  963.     // Create the browser instance component.
  964.     appCore = Components.classes["@mozilla.org/appshell/component/browser/instance;1"]
  965.                         .createInstance(Components.interfaces.nsIBrowserInstance);
  966.     if (!appCore)
  967.       throw "couldn't create a browser instance";
  968.  
  969.     webNavigation = getWebNavigation();
  970.     if (!webNavigation)
  971.       throw "no XBL binding for browser";
  972.   } catch (e) {
  973.     alert("Error launching browser window:" + e);
  974.     window.close(); // Give up.
  975.     return;
  976.   }
  977.  
  978.   // initialize observers and listeners
  979.   // and give C++ access to gBrowser
  980.   XULBrowserWindow.init();
  981.   window.QueryInterface(Ci.nsIInterfaceRequestor)
  982.         .getInterface(nsIWebNavigation)
  983.         .QueryInterface(Ci.nsIDocShellTreeItem).treeOwner
  984.         .QueryInterface(Ci.nsIInterfaceRequestor)
  985.         .getInterface(Ci.nsIXULWindow)
  986.         .XULBrowserWindow = window.XULBrowserWindow;
  987.   window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow =
  988.     new nsBrowserAccess();
  989.  
  990.   // set default character set if provided
  991.   if ("arguments" in window && window.arguments.length > 1 && window.arguments[1]) {
  992.     if (window.arguments[1].indexOf("charset=") != -1) {
  993.       var arrayArgComponents = window.arguments[1].split("=");
  994.       if (arrayArgComponents) {
  995.         //we should "inherit" the charset menu setting in a new window
  996.         getMarkupDocumentViewer().defaultCharacterSet = arrayArgComponents[1];
  997.       }
  998.     }
  999.   }
  1000.  
  1001.   // Initialize browser instance..
  1002.   appCore.setWebShellWindow(window);
  1003.  
  1004.   // Manually hook up session and global history for the first browser
  1005.   // so that we don't have to load global history before bringing up a
  1006.   // window.
  1007.   // Wire up session and global history before any possible
  1008.   // progress notifications for back/forward button updating
  1009.   webNavigation.sessionHistory = Components.classes["@mozilla.org/browser/shistory;1"]
  1010.                                            .createInstance(Components.interfaces.nsISHistory);
  1011.   var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  1012.   os.addObserver(gBrowser.browsers[0], "browser:purge-session-history", false);
  1013.  
  1014.   // remove the disablehistory attribute so the browser cleans up, as
  1015.   // though it had done this work itself
  1016.   gBrowser.browsers[0].removeAttribute("disablehistory");
  1017.  
  1018.   // enable global history
  1019.   try {
  1020.     gBrowser.docShell.QueryInterface(Components.interfaces.nsIDocShellHistory).useGlobalHistory = true;
  1021.   } catch(ex) {
  1022.     Components.utils.reportError("Places database may be locked: " + ex);
  1023.   }
  1024.  
  1025.   // hook up UI through progress listener
  1026.   gBrowser.addProgressListener(window.XULBrowserWindow, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
  1027.   gBrowser.addTabsProgressListener(window.TabsProgressListener);
  1028.  
  1029.   // setup our common DOMLinkAdded listener
  1030.   gBrowser.addEventListener("DOMLinkAdded", DOMLinkHandler, false);
  1031.  
  1032.   // setup our MozApplicationManifest listener
  1033.   gBrowser.addEventListener("MozApplicationManifest",
  1034.                             OfflineApps, false);
  1035.  
  1036.   // setup simple gestures support
  1037.   gGestureSupport.init(true);
  1038. }
  1039.  
  1040. function delayedStartup(isLoadingBlank, mustLoadSidebar) {
  1041.   var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
  1042.   os.addObserver(gSessionHistoryObserver, "browser:purge-session-history", false);
  1043.   os.addObserver(gXPInstallObserver, "xpinstall-install-blocked", false);
  1044.  
  1045.   BrowserOffline.init();
  1046.   OfflineApps.init();
  1047.  
  1048.   gBrowser.addEventListener("pageshow", function(evt) { setTimeout(pageShowEventHandlers, 0, evt); }, true);
  1049.  
  1050.   // Ensure login manager is up and running.
  1051.   Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
  1052.  
  1053.   if (mustLoadSidebar) {
  1054.     let sidebar = document.getElementById("sidebar");
  1055.     let sidebarBox = document.getElementById("sidebar-box");
  1056.     sidebar.setAttribute("src", sidebarBox.getAttribute("src"));
  1057.   }
  1058.  
  1059.   UpdateUrlbarSearchSplitterState();
  1060.   
  1061.   PlacesStarButton.init();
  1062.  
  1063.   // called when we go into full screen, even if it is
  1064.   // initiated by a web page script
  1065.   window.addEventListener("fullscreen", onFullScreen, true);
  1066.  
  1067.   if (isLoadingBlank && gURLBar && isElementVisible(gURLBar))
  1068.     focusElement(gURLBar);
  1069.   else
  1070.     focusElement(content);
  1071.  
  1072.   if (gURLBar)
  1073.     gURLBar.setAttribute("emptytext", gURLBarEmptyText.value);
  1074.  
  1075.   gNavToolbox.customizeDone = BrowserToolboxCustomizeDone;
  1076.   gNavToolbox.customizeChange = BrowserToolboxCustomizeChange;
  1077.  
  1078.   // Set up Sanitize Item
  1079.   initializeSanitizer();
  1080.  
  1081.   // Enable/Disable auto-hide tabbar
  1082.   gAutoHideTabbarPrefListener = new AutoHideTabbarPrefListener();
  1083.   gPrefService.addObserver(gAutoHideTabbarPrefListener.domain,
  1084.                            gAutoHideTabbarPrefListener, false);
  1085.  
  1086.   gPrefService.addObserver(gHomeButton.prefDomain, gHomeButton, false);
  1087.  
  1088.   gPrefService.addObserver(gURLBarEmptyText.domain, gURLBarEmptyText, false);
  1089.  
  1090.   var homeButton = document.getElementById("home-button");
  1091.   gHomeButton.updateTooltip(homeButton);
  1092.   gHomeButton.updatePersonalToolbarStyle(homeButton);
  1093.  
  1094. //@line 1255 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1095.   // Perform default browser checking (after window opens).
  1096.   var shell = getShellService();
  1097.   if (shell) {
  1098.     var shouldCheck = shell.shouldCheckDefaultBrowser;
  1099.     var willRecoverSession = false;
  1100.     try {
  1101.       var ss = Cc["@mozilla.org/browser/sessionstartup;1"].
  1102.                getService(Ci.nsISessionStartup);
  1103.       willRecoverSession =
  1104.         (ss.sessionType == Ci.nsISessionStartup.RECOVER_SESSION);
  1105.     }
  1106.     catch (ex) { /* never mind; suppose SessionStore is broken */ }
  1107.     if (shouldCheck && !shell.isDefaultBrowser(true) && !willRecoverSession) {
  1108.       var brandBundle = document.getElementById("bundle_brand");
  1109.       var shellBundle = document.getElementById("bundle_shell");
  1110.  
  1111.       var brandShortName = brandBundle.getString("brandShortName");
  1112.       var promptTitle = shellBundle.getString("setDefaultBrowserTitle");
  1113.       var promptMessage = shellBundle.getFormattedString("setDefaultBrowserMessage",
  1114.                                                          [brandShortName]);
  1115.       var checkboxLabel = shellBundle.getFormattedString("setDefaultBrowserDontAsk",
  1116.                                                          [brandShortName]);
  1117.       const IPS = Components.interfaces.nsIPromptService;
  1118.       var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
  1119.                                                 .getService(IPS);
  1120.       var checkEveryTime = { value: shouldCheck };
  1121.       var rv = ps.confirmEx(window, promptTitle, promptMessage,
  1122.                             IPS.STD_YES_NO_BUTTONS,
  1123.                             null, null, null, checkboxLabel, checkEveryTime);
  1124.       if (rv == 0)
  1125.         shell.setDefaultBrowser(true, false);
  1126.       shell.shouldCheckDefaultBrowser = checkEveryTime.value;
  1127.     }
  1128.   }
  1129. //@line 1290 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1130.  
  1131.   // BiDi UI
  1132.   gBidiUI = isBidiEnabled();
  1133.   if (gBidiUI) {
  1134.     document.getElementById("documentDirection-separator").hidden = false;
  1135.     document.getElementById("documentDirection-swap").hidden = false;
  1136.     document.getElementById("textfieldDirection-separator").hidden = false;
  1137.     document.getElementById("textfieldDirection-swap").hidden = false;
  1138.   }
  1139.  
  1140. //@line 1306 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1141.  
  1142.   // Initialize the full zoom setting.
  1143.   // We do this before the session restore service gets initialized so we can
  1144.   // apply full zoom settings to tabs restored by the session restore service.
  1145.   try {
  1146.     FullZoom.init();
  1147.   }
  1148.   catch(ex) {
  1149.     Components.utils.reportError("Failed to init content pref service:\n" + ex);
  1150.   }
  1151.  
  1152.   // initialize the session-restore service (in case it's not already running)
  1153.   if (document.documentElement.getAttribute("windowtype") == "navigator:browser") {
  1154.     try {
  1155.       var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  1156.                getService(Ci.nsISessionStore);
  1157.       ss.init(window);
  1158.     } catch(ex) {
  1159.       dump("nsSessionStore could not be initialized: " + ex + "\n");
  1160.     }
  1161.   }
  1162.  
  1163.   // bookmark-all-tabs command
  1164.   gBookmarkAllTabsHandler = new BookmarkAllTabsHandler();
  1165.  
  1166.   // Attach a listener to watch for "command" events bubbling up from error
  1167.   // pages.  This lets us fix bugs like 401575 which require error page UI to
  1168.   // do privileged things, without letting error pages have any privilege
  1169.   // themselves.
  1170.   gBrowser.addEventListener("command", BrowserOnCommand, false);
  1171.  
  1172.   tabPreviews.init();
  1173. //@line 1341 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1174.  
  1175.   // Initialize the microsummary service by retrieving it, prompting its factory
  1176.   // to create its singleton, whose constructor initializes the service.
  1177.   // Started 4 seconds after delayedStartup (before the livemarks service below).
  1178.   setTimeout(function() {
  1179.     try {
  1180.       Cc["@mozilla.org/microsummary/service;1"].getService(Ci.nsIMicrosummaryService);
  1181.     } catch (ex) {
  1182.       Components.utils.reportError("Failed to init microsummary service:\n" + ex);
  1183.     }
  1184.   }, 4000);
  1185.  
  1186.   // Delayed initialization of the livemarks update timer.
  1187.   // Livemark updates don't need to start until after bookmark UI 
  1188.   // such as the toolbar has initialized. Starting 5 seconds after
  1189.   // delayedStartup in order to stagger this after the microsummary
  1190.   // service (see above) and before the download manager starts (see below).
  1191.   setTimeout(function() PlacesUtils.livemarks.start(), 5000);
  1192.  
  1193.   // Initialize the download manager some time after the app starts so that
  1194.   // auto-resume downloads begin (such as after crashing or quitting with
  1195.   // active downloads) and speeds up the first-load of the download manager UI.
  1196.   // If the user manually opens the download manager before the timeout, the
  1197.   // downloads will start right away, and getting the service again won't hurt.
  1198.   setTimeout(function() {
  1199.     gDownloadMgr = Cc["@mozilla.org/download-manager;1"].
  1200.                    getService(Ci.nsIDownloadManager);
  1201.  
  1202.     // Initialize the downloads monitor panel listener
  1203.     DownloadMonitorPanel.init();
  1204.   }, 10000);
  1205.  
  1206.   // Delayed initialization of PlacesDBUtils.
  1207.   // This component checks for database coherence once per day, on
  1208.   // an idle timer, taking corrective actions where needed.
  1209.   setTimeout(function() PlacesUtils.startPlacesDBUtils(), 15000);
  1210.  
  1211. //@line 1379 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1212.   updateEditUIVisibility();
  1213.   let placesContext = document.getElementById("placesContext");
  1214.   placesContext.addEventListener("popupshowing", updateEditUIVisibility, false);
  1215.   placesContext.addEventListener("popuphiding", updateEditUIVisibility, false);
  1216. //@line 1384 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1217.  
  1218.   // initialize the private browsing UI
  1219.   gPrivateBrowsingUI.init();
  1220. }
  1221.  
  1222. function BrowserShutdown()
  1223. {
  1224.   tabPreviews.uninit();
  1225. //@line 1395 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1226.   gGestureSupport.init(false);
  1227.  
  1228.   try {
  1229.     FullZoom.destroy();
  1230.   }
  1231.   catch(ex) {
  1232.     Components.utils.reportError(ex);
  1233.   }
  1234.  
  1235.   var os = Components.classes["@mozilla.org/observer-service;1"]
  1236.     .getService(Components.interfaces.nsIObserverService);
  1237.   os.removeObserver(gSessionHistoryObserver, "browser:purge-session-history");
  1238.   os.removeObserver(gXPInstallObserver, "xpinstall-install-blocked");
  1239.  
  1240.   try {
  1241.     gBrowser.removeProgressListener(window.XULBrowserWindow);
  1242.     gBrowser.removeTabsProgressListener(window.TabsProgressListener);
  1243.   } catch (ex) {
  1244.   }
  1245.  
  1246.   PlacesStarButton.uninit();
  1247.  
  1248.   try {
  1249.     gPrefService.removeObserver(gAutoHideTabbarPrefListener.domain,
  1250.                                 gAutoHideTabbarPrefListener);
  1251.     gPrefService.removeObserver(gHomeButton.prefDomain, gHomeButton);
  1252.     gPrefService.removeObserver(gURLBarEmptyText.domain, gURLBarEmptyText);
  1253.   } catch (ex) {
  1254.     Components.utils.reportError(ex);
  1255.   }
  1256.  
  1257.   BrowserOffline.uninit();
  1258.   OfflineApps.uninit();
  1259.   DownloadMonitorPanel.uninit();
  1260.   gPrivateBrowsingUI.uninit();
  1261.  
  1262.   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  1263.   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  1264.   var enumerator = windowManagerInterface.getEnumerator(null);
  1265.   enumerator.getNext();
  1266.   if (!enumerator.hasMoreElements()) {
  1267.     document.persist("sidebar-box", "sidebarcommand");
  1268.     document.persist("sidebar-box", "width");
  1269.     document.persist("sidebar-box", "src");
  1270.     document.persist("sidebar-title", "value");
  1271.   }
  1272.  
  1273.   window.XULBrowserWindow.destroy();
  1274.   window.XULBrowserWindow = null;
  1275.   window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  1276.         .getInterface(Components.interfaces.nsIWebNavigation)
  1277.         .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner
  1278.         .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  1279.         .getInterface(Components.interfaces.nsIXULWindow)
  1280.         .XULBrowserWindow = null;
  1281.   window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow = null;
  1282.  
  1283.   // Close the app core.
  1284.   if (appCore)
  1285.     appCore.close();
  1286. }
  1287.  
  1288. //@line 1518 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1289.  
  1290. function AutoHideTabbarPrefListener()
  1291. {
  1292.   this.toggleAutoHideTabbar();
  1293. }
  1294.  
  1295. AutoHideTabbarPrefListener.prototype =
  1296. {
  1297.   domain: "browser.tabs.autoHide",
  1298.   observe: function (aSubject, aTopic, aPrefName)
  1299.   {
  1300.     if (aTopic != "nsPref:changed" || aPrefName != this.domain)
  1301.       return;
  1302.  
  1303.     this.toggleAutoHideTabbar();
  1304.   },
  1305.  
  1306.   toggleAutoHideTabbar: function ()
  1307.   {
  1308.     if (gBrowser.tabContainer.childNodes.length == 1 &&
  1309.         window.toolbar.visible) {
  1310.       var aVisible = false;
  1311.       try {
  1312.         aVisible = !gPrefService.getBoolPref(this.domain);
  1313.       }
  1314.       catch (e) {
  1315.       }
  1316.       gBrowser.setStripVisibilityTo(aVisible);
  1317.     }
  1318.   }
  1319. }
  1320.  
  1321. function initializeSanitizer()
  1322. {
  1323.   // Always use the label with ellipsis
  1324.   var label = gNavigatorBundle.getString("sanitizeWithPromptLabel2");
  1325.   document.getElementById("sanitizeItem").setAttribute("label", label);
  1326.  
  1327.   const kDidSanitizeDomain = "privacy.sanitize.didShutdownSanitize";
  1328.   if (gPrefService.prefHasUserValue(kDidSanitizeDomain)) {
  1329.     gPrefService.clearUserPref(kDidSanitizeDomain);
  1330.     // We need to persist this preference change, since we want to
  1331.     // check it at next app start even if the browser exits abruptly
  1332.     gPrefService.QueryInterface(Ci.nsIPrefService).savePrefFile(null);
  1333.   }
  1334.  
  1335.   /**
  1336.    * Migrate Firefox 3.0 privacy.item prefs under one of these conditions:
  1337.    *
  1338.    * a) User has customized any privacy.item prefs
  1339.    * b) privacy.sanitize.sanitizeOnShutdown is set
  1340.    */
  1341.   (function() {
  1342.     var prefService = Cc["@mozilla.org/preferences-service;1"].
  1343.                       getService(Ci.nsIPrefService);
  1344.     if (!prefService.getBoolPref("privacy.sanitize.migrateFx3Prefs")) {
  1345.       var itemBranch = prefService.getBranch("privacy.item.");
  1346.       var itemCount = { value: 0 };
  1347.       var itemArray = itemBranch.getChildList("", itemCount);
  1348.  
  1349.       // See if any privacy.item prefs are set
  1350.       var doMigrate = itemArray.some(function (name) itemBranch.prefHasUserValue(name));
  1351.       // Or if sanitizeOnShutdown is set
  1352.       if (!doMigrate)
  1353.         doMigrate = prefService.getBoolPref("privacy.sanitize.sanitizeOnShutdown");
  1354.  
  1355.       if (doMigrate) {
  1356.         var cpdBranch = prefService.getBranch("privacy.cpd.");
  1357.         var clearOnShutdownBranch = prefService.getBranch("privacy.clearOnShutdown.");
  1358.         itemArray.forEach(function (name) {
  1359.           try {
  1360.             // don't migrate password or offlineApps clearing in the CRH dialog since
  1361.             // there's no UI for those anymore. They default to false. bug 497656
  1362.             if (name != "passwords" && name != "offlineApps")
  1363.               cpdBranch.setBoolPref(name, itemBranch.getBoolPref(name));
  1364.             clearOnShutdownBranch.setBoolPref(name, itemBranch.getBoolPref(name));
  1365.           }
  1366.           catch(e) {
  1367.             Components.utils.reportError("Exception thrown during privacy pref migration: " + e);
  1368.           }
  1369.         });
  1370.       }
  1371.  
  1372.       prefService.setBoolPref("privacy.sanitize.migrateFx3Prefs", true);
  1373.     }
  1374.   })();
  1375. }
  1376.  
  1377. function gotoHistoryIndex(aEvent)
  1378. {
  1379.   var index = aEvent.target.getAttribute("index");
  1380.   if (!index)
  1381.     return false;
  1382.  
  1383.   var where = whereToOpenLink(aEvent);
  1384.  
  1385.   if (where == "current") {
  1386.     // Normal click.  Go there in the current tab and update session history.
  1387.  
  1388.     try {
  1389.       gBrowser.gotoIndex(index);
  1390.     }
  1391.     catch(ex) {
  1392.       return false;
  1393.     }
  1394.     return true;
  1395.   }
  1396.   else {
  1397.     // Modified click.  Go there in a new tab/window.
  1398.     // This code doesn't copy history or work well with framed pages.
  1399.  
  1400.     var sessionHistory = getWebNavigation().sessionHistory;
  1401.     var entry = sessionHistory.getEntryAtIndex(index, false);
  1402.     var url = entry.URI.spec;
  1403.     openUILinkIn(url, where);
  1404.     return true;
  1405.   }
  1406. }
  1407.  
  1408. function BrowserForward(aEvent) {
  1409.   var where = whereToOpenLink(aEvent, false, true);
  1410.  
  1411.   if (where == "current") {
  1412.     try {
  1413.       gBrowser.goForward();
  1414.     }
  1415.     catch(ex) {
  1416.     }
  1417.   }
  1418.   else {
  1419.     var sessionHistory = getWebNavigation().sessionHistory;
  1420.     var currentIndex = sessionHistory.index;
  1421.     var entry = sessionHistory.getEntryAtIndex(currentIndex + 1, false);
  1422.     var url = entry.URI.spec;
  1423.     openUILinkIn(url, where);
  1424.   }
  1425. }
  1426.  
  1427. function BrowserBack(aEvent) {
  1428.   var where = whereToOpenLink(aEvent, false, true);
  1429.  
  1430.   if (where == "current") {
  1431.     try {
  1432.       gBrowser.goBack();
  1433.     }
  1434.     catch(ex) {
  1435.     }
  1436.   }
  1437.   else {
  1438.     var sessionHistory = getWebNavigation().sessionHistory;
  1439.     var currentIndex = sessionHistory.index;
  1440.     var entry = sessionHistory.getEntryAtIndex(currentIndex - 1, false);
  1441.     var url = entry.URI.spec;
  1442.     openUILinkIn(url, where);
  1443.   }
  1444. }
  1445.  
  1446. function BrowserHandleBackspace()
  1447. {
  1448.   switch (gPrefService.getIntPref("browser.backspace_action")) {
  1449.   case 0:
  1450.     BrowserBack();
  1451.     break;
  1452.   case 1:
  1453.     goDoCommand("cmd_scrollPageUp");
  1454.     break;
  1455.   }
  1456. }
  1457.  
  1458. function BrowserHandleShiftBackspace()
  1459. {
  1460.   switch (gPrefService.getIntPref("browser.backspace_action")) {
  1461.   case 0:
  1462.     BrowserForward();
  1463.     break;
  1464.   case 1:
  1465.     goDoCommand("cmd_scrollPageDown");
  1466.     break;
  1467.   }
  1468. }
  1469.  
  1470. function BrowserStop()
  1471. {
  1472.   try {
  1473.     const stopFlags = nsIWebNavigation.STOP_ALL;
  1474.     getWebNavigation().stop(stopFlags);
  1475.   }
  1476.   catch(ex) {
  1477.   }
  1478. }
  1479.  
  1480. function BrowserReloadOrDuplicate(aEvent) {
  1481.   var backgroundTabModifier = aEvent.button == 1 ||
  1482. //@line 1714 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1483.     aEvent.ctrlKey;
  1484. //@line 1716 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1485.   if (aEvent.shiftKey && !backgroundTabModifier) {
  1486.     BrowserReloadSkipCache();
  1487.     return;
  1488.   }
  1489.  
  1490.   var where = whereToOpenLink(aEvent, false, true);
  1491.   if (where == "current")
  1492.     BrowserReload();
  1493.   else
  1494.     openUILinkIn(getWebNavigation().currentURI.spec, where);
  1495. }
  1496.  
  1497. function BrowserReload() {
  1498.   const reloadFlags = nsIWebNavigation.LOAD_FLAGS_NONE;
  1499.   BrowserReloadWithFlags(reloadFlags);
  1500. }
  1501.  
  1502. function BrowserReloadSkipCache() {
  1503.   // Bypass proxy and cache.
  1504.   const reloadFlags = nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
  1505.   BrowserReloadWithFlags(reloadFlags);
  1506. }
  1507.  
  1508. function BrowserHome()
  1509. {
  1510.   var homePage = gHomeButton.getHomePage();
  1511.   loadOneOrMoreURIs(homePage);
  1512. }
  1513.  
  1514. function BrowserGoHome(aEvent) {
  1515.   if (aEvent && "button" in aEvent &&
  1516.       aEvent.button == 2) // right-click: do nothing
  1517.     return;
  1518.  
  1519.   var homePage = gHomeButton.getHomePage();
  1520.   var where = whereToOpenLink(aEvent, false, true);
  1521.   var urls;
  1522.  
  1523.   // openUILinkIn in utilityOverlay.js doesn't handle loading multiple pages
  1524.   switch (where) {
  1525.   case "current":
  1526.     loadOneOrMoreURIs(homePage);
  1527.     break;
  1528.   case "tabshifted":
  1529.   case "tab":
  1530.     urls = homePage.split("|");
  1531.     var loadInBackground = getBoolPref("browser.tabs.loadBookmarksInBackground", false);
  1532.     gBrowser.loadTabs(urls, loadInBackground);
  1533.     break;
  1534.   case "window":
  1535.     OpenBrowserWindow();
  1536.     break;
  1537.   }
  1538. }
  1539.  
  1540. function loadOneOrMoreURIs(aURIString)
  1541. {
  1542. //@line 1781 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1543.   // This function throws for certain malformed URIs, so use exception handling
  1544.   // so that we don't disrupt startup
  1545.   try {
  1546.     gBrowser.loadTabs(aURIString.split("|"), false, true);
  1547.   } 
  1548.   catch (e) {
  1549.   }
  1550. }
  1551.  
  1552. function focusAndSelectUrlBar() {
  1553.   if (gURLBar && isElementVisible(gURLBar) && !gURLBar.readOnly) {
  1554.     gURLBar.focus();
  1555.     gURLBar.select();
  1556.     return true;
  1557.   }
  1558.   return false;
  1559. }
  1560.  
  1561. function openLocation() {
  1562.   if (window.fullScreen)
  1563.     FullScreen.mouseoverToggle(true);
  1564.  
  1565.   if (focusAndSelectUrlBar())
  1566.     return;
  1567. //@line 1822 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1568.   openDialog("chrome://browser/content/openLocation.xul", "_blank",
  1569.              "chrome,modal,titlebar", window);
  1570. }
  1571.  
  1572. function openLocationCallback()
  1573. {
  1574.   // make sure the DOM is ready
  1575.   setTimeout(function() { this.openLocation(); }, 0);
  1576. }
  1577.  
  1578. function BrowserOpenTab()
  1579. {
  1580.   if (!gBrowser) {
  1581.     // If there are no open browser windows, open a new one
  1582.     window.openDialog("chrome://browser/content/", "_blank",
  1583.                       "chrome,all,dialog=no", "about:blank");
  1584.     return;
  1585.   }
  1586.   gBrowser.loadOneTab("about:blank", null, null, null, false, false);
  1587.   if (gURLBar)
  1588.     gURLBar.focus();
  1589. }
  1590.  
  1591. /* Called from the openLocation dialog. This allows that dialog to instruct
  1592.    its opener to open a new window and then step completely out of the way.
  1593.    Anything less byzantine is causing horrible crashes, rather believably,
  1594.    though oddly only on Linux. */
  1595. function delayedOpenWindow(chrome, flags, href, postData)
  1596. {
  1597.   // The other way to use setTimeout,
  1598.   // setTimeout(openDialog, 10, chrome, "_blank", flags, url),
  1599.   // doesn't work here.  The extra "magic" extra argument setTimeout adds to
  1600.   // the callback function would confuse prepareForStartup() by making
  1601.   // window.arguments[1] be an integer instead of null.
  1602.   setTimeout(function() { openDialog(chrome, "_blank", flags, href, null, null, postData); }, 10);
  1603. }
  1604.  
  1605. /* Required because the tab needs time to set up its content viewers and get the load of
  1606.    the URI kicked off before becoming the active content area. */
  1607. function delayedOpenTab(aUrl, aReferrer, aCharset, aPostData, aAllowThirdPartyFixup)
  1608. {
  1609.   gBrowser.loadOneTab(aUrl, aReferrer, aCharset, aPostData, false, aAllowThirdPartyFixup);
  1610. }
  1611.  
  1612. function BrowserOpenFileWindow()
  1613. {
  1614.   // Get filepicker component.
  1615.   try {
  1616.     const nsIFilePicker = Components.interfaces.nsIFilePicker;
  1617.     var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  1618.     fp.init(window, gNavigatorBundle.getString("openFile"), nsIFilePicker.modeOpen);
  1619.     fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText | nsIFilePicker.filterImages |
  1620.                      nsIFilePicker.filterXML | nsIFilePicker.filterHTML);
  1621.  
  1622.     if (fp.show() == nsIFilePicker.returnOK)
  1623.       openTopWin(fp.fileURL.spec);
  1624.   } catch (ex) {
  1625.   }
  1626. }
  1627.  
  1628. function BrowserCloseTabOrWindow() {
  1629. //@line 1890 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1630.  
  1631.   // If the current tab is the last one, this will close the window.
  1632.   gBrowser.removeCurrentTab();
  1633. }
  1634.  
  1635. function BrowserTryToCloseWindow()
  1636. {
  1637.   if (WindowIsClosing()) {
  1638.     if (window.fullScreen) {
  1639.       gBrowser.mPanelContainer.removeEventListener("mousemove",
  1640.                                                    FullScreen._collapseCallback, false);
  1641.       document.removeEventListener("keypress", FullScreen._keyToggleCallback, false);
  1642.       document.removeEventListener("popupshown", FullScreen._setPopupOpen, false);
  1643.       document.removeEventListener("popuphidden", FullScreen._setPopupOpen, false);
  1644.       gPrefService.removeObserver("browser.fullscreen", FullScreen);
  1645.  
  1646.       var fullScrToggler = document.getElementById("fullscr-toggler");
  1647.       if (fullScrToggler) {
  1648.         fullScrToggler.removeEventListener("mouseover", FullScreen._expandCallback, false);
  1649.         fullScrToggler.removeEventListener("dragenter", FullScreen._expandCallback, false);
  1650.       }
  1651.     }
  1652.  
  1653.     window.close();     // WindowIsClosing does all the necessary checks
  1654.   }
  1655. }
  1656.  
  1657. function loadURI(uri, referrer, postData, allowThirdPartyFixup)
  1658. {
  1659.   try {
  1660.     if (postData === undefined)
  1661.       postData = null;
  1662.     var flags = nsIWebNavigation.LOAD_FLAGS_NONE;
  1663.     if (allowThirdPartyFixup) {
  1664.       flags = nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
  1665.     }
  1666.     gBrowser.loadURIWithFlags(uri, flags, referrer, null, postData);
  1667.   } catch (e) {
  1668.   }
  1669. }
  1670.  
  1671. function getShortcutOrURI(aURL, aPostDataRef) {
  1672.   var shortcutURL = null;
  1673.   var keyword = aURL;
  1674.   var param = "";
  1675.   var searchService = Cc["@mozilla.org/browser/search-service;1"].
  1676.                       getService(Ci.nsIBrowserSearchService);
  1677.  
  1678.   var offset = aURL.indexOf(" ");
  1679.   if (offset > 0) {
  1680.     keyword = aURL.substr(0, offset);
  1681.     param = aURL.substr(offset + 1);
  1682.   }
  1683.  
  1684.   if (!aPostDataRef)
  1685.     aPostDataRef = {};
  1686.  
  1687.   var engine = searchService.getEngineByAlias(keyword);
  1688.   if (engine) {
  1689.     var submission = engine.getSubmission(param, null);
  1690.     aPostDataRef.value = submission.postData;
  1691.     return submission.uri.spec;
  1692.   }
  1693.  
  1694.   [shortcutURL, aPostDataRef.value] =
  1695.     PlacesUtils.getURLAndPostDataForKeyword(keyword);
  1696.  
  1697.   if (!shortcutURL)
  1698.     return aURL;
  1699.  
  1700.   var postData = "";
  1701.   if (aPostDataRef.value)
  1702.     postData = unescape(aPostDataRef.value);
  1703.  
  1704.   if (/%s/i.test(shortcutURL) || /%s/i.test(postData)) {
  1705.     var charset = "";
  1706.     const re = /^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/;
  1707.     var matches = shortcutURL.match(re);
  1708.     if (matches)
  1709.       [, shortcutURL, charset] = matches;
  1710.     else {
  1711.       // Try to get the saved character-set.
  1712.       try {
  1713.         // makeURI throws if URI is invalid.
  1714.         // Will return an empty string if character-set is not found.
  1715.         charset = PlacesUtils.history.getCharsetForURI(makeURI(shortcutURL));
  1716.       } catch (e) {}
  1717.     }
  1718.  
  1719.     var encodedParam = "";
  1720.     if (charset)
  1721.       encodedParam = escape(convertFromUnicode(charset, param));
  1722.     else // Default charset is UTF-8
  1723.       encodedParam = encodeURIComponent(param);
  1724.  
  1725.     shortcutURL = shortcutURL.replace(/%s/g, encodedParam).replace(/%S/g, param);
  1726.  
  1727.     if (/%s/i.test(postData)) // POST keyword
  1728.       aPostDataRef.value = getPostDataStream(postData, param, encodedParam,
  1729.                                              "application/x-www-form-urlencoded");
  1730.   }
  1731.   else if (param) {
  1732.     // This keyword doesn't take a parameter, but one was provided. Just return
  1733.     // the original URL.
  1734.     aPostDataRef.value = null;
  1735.  
  1736.     return aURL;
  1737.   }
  1738.  
  1739.   return shortcutURL;
  1740. }
  1741.  
  1742. function getPostDataStream(aStringData, aKeyword, aEncKeyword, aType) {
  1743.   var dataStream = Cc["@mozilla.org/io/string-input-stream;1"].
  1744.                    createInstance(Ci.nsIStringInputStream);
  1745.   aStringData = aStringData.replace(/%s/g, aEncKeyword).replace(/%S/g, aKeyword);
  1746.   dataStream.data = aStringData;
  1747.  
  1748.   var mimeStream = Cc["@mozilla.org/network/mime-input-stream;1"].
  1749.                    createInstance(Ci.nsIMIMEInputStream);
  1750.   mimeStream.addHeader("Content-Type", aType);
  1751.   mimeStream.addContentLength = true;
  1752.   mimeStream.setData(dataStream);
  1753.   return mimeStream.QueryInterface(Ci.nsIInputStream);
  1754. }
  1755.  
  1756. function readFromClipboard()
  1757. {
  1758.   var url;
  1759.  
  1760.   try {
  1761.     // Get clipboard.
  1762.     var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
  1763.                               .getService(Components.interfaces.nsIClipboard);
  1764.  
  1765.     // Create tranferable that will transfer the text.
  1766.     var trans = Components.classes["@mozilla.org/widget/transferable;1"]
  1767.                           .createInstance(Components.interfaces.nsITransferable);
  1768.  
  1769.     trans.addDataFlavor("text/unicode");
  1770.  
  1771.     // If available, use selection clipboard, otherwise global one
  1772.     if (clipboard.supportsSelectionClipboard())
  1773.       clipboard.getData(trans, clipboard.kSelectionClipboard);
  1774.     else
  1775.       clipboard.getData(trans, clipboard.kGlobalClipboard);
  1776.  
  1777.     var data = {};
  1778.     var dataLen = {};
  1779.     trans.getTransferData("text/unicode", data, dataLen);
  1780.  
  1781.     if (data) {
  1782.       data = data.value.QueryInterface(Components.interfaces.nsISupportsString);
  1783.       url = data.data.substring(0, dataLen.value / 2);
  1784.     }
  1785.   } catch (ex) {
  1786.   }
  1787.  
  1788.   return url;
  1789. }
  1790.  
  1791. function BrowserViewSourceOfDocument(aDocument)
  1792. {
  1793.   var pageCookie;
  1794.   var webNav;
  1795.  
  1796.   // Get the document charset
  1797.   var docCharset = "charset=" + aDocument.characterSet;
  1798.  
  1799.   // Get the nsIWebNavigation associated with the document
  1800.   try {
  1801.       var win;
  1802.       var ifRequestor;
  1803.  
  1804.       // Get the DOMWindow for the requested document.  If the DOMWindow
  1805.       // cannot be found, then just use the content window...
  1806.       //
  1807.       // XXX:  This is a bit of a hack...
  1808.       win = aDocument.defaultView;
  1809.       if (win == window) {
  1810.         win = content;
  1811.       }
  1812.       ifRequestor = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  1813.  
  1814.       webNav = ifRequestor.getInterface(nsIWebNavigation);
  1815.   } catch(err) {
  1816.       // If nsIWebNavigation cannot be found, just get the one for the whole
  1817.       // window...
  1818.       webNav = getWebNavigation();
  1819.   }
  1820.   //
  1821.   // Get the 'PageDescriptor' for the current document. This allows the
  1822.   // view-source to access the cached copy of the content rather than
  1823.   // refetching it from the network...
  1824.   //
  1825.   try{
  1826.     var PageLoader = webNav.QueryInterface(Components.interfaces.nsIWebPageDescriptor);
  1827.  
  1828.     pageCookie = PageLoader.currentDescriptor;
  1829.   } catch(err) {
  1830.     // If no page descriptor is available, just use the view-source URL...
  1831.   }
  1832.  
  1833.   top.gViewSourceUtils.viewSource(webNav.currentURI.spec, pageCookie, aDocument);
  1834. }
  1835.  
  1836. // doc - document to use for source, or null for this window's document
  1837. // initialTab - name of the initial tab to display, or null for the first tab
  1838. function BrowserPageInfo(doc, initialTab)
  1839. {
  1840.   var args = {doc: doc, initialTab: initialTab};
  1841.   return toOpenDialogByTypeAndUrl("Browser:page-info",
  1842.                                   doc ? doc.location : window.content.document.location,
  1843.                                   "chrome://browser/content/pageinfo/pageInfo.xul",
  1844.                                   "chrome,toolbar,dialog=no,resizable",
  1845.                                   args);
  1846. }
  1847.  
  1848. //@line 2157 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  1849.  
  1850. function URLBarSetURI(aURI, aValid) {
  1851.   var value = gBrowser.userTypedValue;
  1852.   var valid = false;
  1853.  
  1854.   if (value == null) {
  1855.     let uri = aURI || getWebNavigation().currentURI;
  1856.  
  1857.     // Replace initial page URIs with an empty string
  1858.     // only if there's no opener (bug 370555).
  1859.     if (gInitialPages.indexOf(uri.spec) != -1)
  1860.       value = content.opener ? uri.spec : "";
  1861.     else
  1862.       value = losslessDecodeURI(uri);
  1863.  
  1864.     let isBlank = (uri.spec == "about:blank");
  1865.     valid = !isBlank && (!aURI || aValid);
  1866.   }
  1867.  
  1868.   gURLBar.value = value;
  1869.   SetPageProxyState(valid ? "valid" : "invalid");
  1870. }
  1871.  
  1872. function losslessDecodeURI(aURI) {
  1873.   var value = aURI.spec;
  1874.   // Try to decode as UTF-8 if there's no encoding sequence that we would break.
  1875.   if (!/%25(?:3B|2F|3F|3A|40|26|3D|2B|24|2C|23)/i.test(value))
  1876.     try {
  1877.       value = decodeURI(value)
  1878.                 // 1. decodeURI decodes %25 to %, which creates unintended
  1879.                 //    encoding sequences. Re-encode it, unless it's part of
  1880.                 //    a sequence that survived decodeURI, i.e. one for:
  1881.                 //    ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '#'
  1882.                 //    (RFC 3987 section 3.2)
  1883.                 // 2. Re-encode whitespace so that it doesn't get eaten away
  1884.                 //    by the location bar (bug 410726).
  1885.                 .replace(/%(?!3B|2F|3F|3A|40|26|3D|2B|24|2C|23)|[\r\n\t]/ig,
  1886.                          encodeURIComponent);
  1887.     } catch (e) {}
  1888.  
  1889.   // Encode invisible characters (soft hyphen, zero-width space, BOM,
  1890.   // line and paragraph separator, word joiner, invisible times,
  1891.   // invisible separator, object replacement character) (bug 452979)
  1892.   value = value.replace(/[\v\x0c\x1c\x1d\x1e\x1f\u00ad\u200b\ufeff\u2028\u2029\u2060\u2062\u2063\ufffc]/g,
  1893.                         encodeURIComponent);
  1894.  
  1895.   // Encode bidirectional formatting characters.
  1896.   // (RFC 3987 sections 3.2 and 4.1 paragraph 6)
  1897.   value = value.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g,
  1898.                         encodeURIComponent);
  1899.   return value;
  1900. }
  1901.  
  1902. function UpdateUrlbarSearchSplitterState()
  1903. {
  1904.   var splitter = document.getElementById("urlbar-search-splitter");
  1905.   var urlbar = document.getElementById("urlbar-container");
  1906.   var searchbar = document.getElementById("search-container");
  1907.  
  1908.   var ibefore = null;
  1909.   if (urlbar && searchbar) {
  1910.     if (urlbar.nextSibling == searchbar)
  1911.       ibefore = searchbar;
  1912.     else if (searchbar.nextSibling == urlbar)
  1913.       ibefore = urlbar;
  1914.   }
  1915.  
  1916.   if (ibefore) {
  1917.     if (!splitter) {
  1918.       splitter = document.createElement("splitter");
  1919.       splitter.id = "urlbar-search-splitter";
  1920.       splitter.setAttribute("resizebefore", "flex");
  1921.       splitter.setAttribute("resizeafter", "flex");
  1922.       splitter.className = "chromeclass-toolbar-additional";
  1923.     }
  1924.     urlbar.parentNode.insertBefore(splitter, ibefore);
  1925.   } else if (splitter)
  1926.     splitter.parentNode.removeChild(splitter);
  1927. }
  1928.  
  1929. var LocationBarHelpers = {
  1930.   _timeoutID: null,
  1931.  
  1932.   _searchBegin: function LocBar_searchBegin() {
  1933.     function delayedBegin(self) {
  1934.       self._timeoutID = null;
  1935.       document.getElementById("urlbar-throbber").setAttribute("busy", "true");
  1936.     }
  1937.  
  1938.     this._timeoutID = setTimeout(delayedBegin, 500, this);
  1939.   },
  1940.  
  1941.   _searchComplete: function LocBar_searchComplete() {
  1942.     // Did we finish the search before delayedBegin was invoked?
  1943.     if (this._timeoutID) {
  1944.       clearTimeout(this._timeoutID);
  1945.       this._timeoutID = null;
  1946.     }
  1947.     document.getElementById("urlbar-throbber").removeAttribute("busy");
  1948.   }
  1949. };
  1950.  
  1951. function UpdatePageProxyState()
  1952. {
  1953.   if (gURLBar && gURLBar.value != gLastValidURLStr)
  1954.     SetPageProxyState("invalid");
  1955. }
  1956.  
  1957. function SetPageProxyState(aState)
  1958. {
  1959.   if (!gURLBar)
  1960.     return;
  1961.  
  1962.   if (!gProxyFavIcon)
  1963.     gProxyFavIcon = document.getElementById("page-proxy-favicon");
  1964.  
  1965.   gURLBar.setAttribute("pageproxystate", aState);
  1966.   gProxyFavIcon.setAttribute("pageproxystate", aState);
  1967.  
  1968.   // the page proxy state is set to valid via OnLocationChange, which
  1969.   // gets called when we switch tabs.
  1970.   if (aState == "valid") {
  1971.     gLastValidURLStr = gURLBar.value;
  1972.     gURLBar.addEventListener("input", UpdatePageProxyState, false);
  1973.  
  1974.     PageProxySetIcon(gBrowser.mCurrentBrowser.mIconURL);
  1975.   } else if (aState == "invalid") {
  1976.     gURLBar.removeEventListener("input", UpdatePageProxyState, false);
  1977.     PageProxyClearIcon();
  1978.   }
  1979. }
  1980.  
  1981. function PageProxySetIcon (aURL)
  1982. {
  1983.   if (!gProxyFavIcon)
  1984.     return;
  1985.  
  1986.   if (!aURL)
  1987.     PageProxyClearIcon();
  1988.   else if (gProxyFavIcon.getAttribute("src") != aURL)
  1989.     gProxyFavIcon.setAttribute("src", aURL);
  1990. }
  1991.  
  1992. function PageProxyClearIcon ()
  1993. {
  1994.   gProxyFavIcon.removeAttribute("src");
  1995. }
  1996.  
  1997.  
  1998. function PageProxyDragGesture(aEvent)
  1999. {
  2000.   if (gProxyFavIcon.getAttribute("pageproxystate") == "valid") {
  2001.     nsDragAndDrop.startDrag(aEvent, proxyIconDNDObserver);
  2002.     return true;
  2003.   }
  2004.   return false;
  2005. }
  2006.  
  2007. function PageProxyClickHandler(aEvent)
  2008. {
  2009.   if (aEvent.button == 1 && gPrefService.getBoolPref("middlemouse.paste"))
  2010.     middleMousePaste(aEvent);
  2011. }
  2012.  
  2013. function BrowserImport()
  2014. {
  2015. //@line 2334 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  2016.   window.openDialog("chrome://browser/content/migration/migration.xul",
  2017.                     "migration", "modal,centerscreen,chrome,resizable=no");
  2018. //@line 2337 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  2019. }
  2020.  
  2021. /**
  2022.  * Handle command events bubbling up from error page content
  2023.  */
  2024. function BrowserOnCommand(event) {
  2025.     // Don't trust synthetic events
  2026.     if (!event.isTrusted)
  2027.       return;
  2028.  
  2029.     var ot = event.originalTarget;
  2030.     var errorDoc = ot.ownerDocument;
  2031.  
  2032.     // If the event came from an ssl error page, it is probably either the "Add
  2033.     // Exception…" or "Get me out of here!" button
  2034.     if (/^about:certerror/.test(errorDoc.documentURI)) {
  2035.       if (ot == errorDoc.getElementById('exceptionDialogButton')) {
  2036.         var params = { exceptionAdded : false };
  2037.         
  2038.         try {
  2039.           switch (gPrefService.getIntPref("browser.ssl_override_behavior")) {
  2040.             case 2 : // Pre-fetch & pre-populate
  2041.               params.prefetchCert = true;
  2042.             case 1 : // Pre-populate
  2043.               params.location = errorDoc.location.href;
  2044.           }
  2045.         } catch (e) {
  2046.           Components.utils.reportError("Couldn't get ssl_override pref: " + e);
  2047.         }
  2048.         
  2049.         window.openDialog('chrome://pippki/content/exceptionDialog.xul',
  2050.                           '','chrome,centerscreen,modal', params);
  2051.         
  2052.         // If the user added the exception cert, attempt to reload the page
  2053.         if (params.exceptionAdded)
  2054.           errorDoc.location.reload();
  2055.       }
  2056.       else if (ot == errorDoc.getElementById('getMeOutOfHereButton')) {
  2057.         getMeOutOfHere();
  2058.       }
  2059.     }
  2060.     else if (/^about:blocked/.test(errorDoc.documentURI)) {
  2061.       // The event came from a button on a malware/phishing block page
  2062.       // First check whether it's malware or phishing, so that we can
  2063.       // use the right strings/links
  2064.       var isMalware = /e=malwareBlocked/.test(errorDoc.documentURI);
  2065.       
  2066.       if (ot == errorDoc.getElementById('getMeOutButton')) {
  2067.         getMeOutOfHere();
  2068.       }
  2069.       else if (ot == errorDoc.getElementById('reportButton')) {
  2070.         // This is the "Why is this site blocked" button.  For malware,
  2071.         // we can fetch a site-specific report, for phishing, we redirect
  2072.         // to the generic page describing phishing protection.
  2073.         var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"]
  2074.                        .getService(Components.interfaces.nsIURLFormatter);
  2075.         
  2076.         if (isMalware) {
  2077.           // Get the stop badware "why is this blocked" report url,
  2078.           // append the current url, and go there.
  2079.           try {
  2080.             var reportURL = formatter.formatURLPref("browser.safebrowsing.malware.reportURL");
  2081.             reportURL += errorDoc.location.href;
  2082.             content.location = reportURL;
  2083.           } catch (e) {
  2084.             Components.utils.reportError("Couldn't get malware report URL: " + e);
  2085.           }
  2086.         }
  2087.         else { // It's a phishing site, not malware
  2088.           try {
  2089.             content.location = formatter.formatURLPref("browser.safebrowsing.warning.infoURL");
  2090.           } catch (e) {
  2091.             Components.utils.reportError("Couldn't get phishing info URL: " + e);
  2092.           }
  2093.         }
  2094.       }
  2095.       else if (ot == errorDoc.getElementById('ignoreWarningButton')) {
  2096.         // Allow users to override and continue through to the site,
  2097.         // but add a notify bar as a reminder, so that they don't lose
  2098.         // track after, e.g., tab switching.
  2099.         gBrowser.loadURIWithFlags(content.location.href,
  2100.                                   nsIWebNavigation.LOAD_FLAGS_BYPASS_CLASSIFIER,
  2101.                                   null, null, null);
  2102.         var buttons = [{
  2103.           label: gNavigatorBundle.getString("safebrowsing.getMeOutOfHereButton.label"),
  2104.           accessKey: gNavigatorBundle.getString("safebrowsing.getMeOutOfHereButton.accessKey"),
  2105.           callback: function() { getMeOutOfHere(); }
  2106.         }];
  2107.         
  2108.         if (isMalware) {
  2109.           var title = gNavigatorBundle.getString("safebrowsing.reportedAttackSite");
  2110.           buttons[1] = {
  2111.             label: gNavigatorBundle.getString("safebrowsing.notAnAttackButton.label"),
  2112.             accessKey: gNavigatorBundle.getString("safebrowsing.notAnAttackButton.accessKey"),
  2113.             callback: function() {
  2114.               openUILinkIn(safebrowsing.getReportURL('MalwareError'), 'tab');
  2115.             }
  2116.           };
  2117.         } else {
  2118.           title = gNavigatorBundle.getString("safebrowsing.reportedWebForgery");
  2119.           buttons[1] = {
  2120.             label: gNavigatorBundle.getString("safebrowsing.notAForgeryButton.label"),
  2121.             accessKey: gNavigatorBundle.getString("safebrowsing.notAForgeryButton.accessKey"),
  2122.             callback: function() {
  2123.               openUILinkIn(safebrowsing.getReportURL('Error'), 'tab');
  2124.             }
  2125.           };
  2126.         }
  2127.         
  2128.         var notificationBox = gBrowser.getNotificationBox();
  2129.         notificationBox.appendNotification(
  2130.           title,
  2131.           "blocked-badware-page",
  2132.           "chrome://global/skin/icons/blacklist_favicon.png",
  2133.           notificationBox.PRIORITY_CRITICAL_HIGH,
  2134.           buttons
  2135.         );
  2136.       }
  2137.     }
  2138.     else if (/^about:privatebrowsing/.test(errorDoc.documentURI)) {
  2139.       if (ot == errorDoc.getElementById("startPrivateBrowsing")) {
  2140.         gPrivateBrowsingUI.toggleMode();
  2141.       }
  2142.     }
  2143. }
  2144.  
  2145. /**
  2146.  * Re-direct the browser to a known-safe page.  This function is
  2147.  * used when, for example, the user browses to a known malware page
  2148.  * and is presented with about:blocked.  The "Get me out of here!"
  2149.  * button should take the user to the default start page so that even
  2150.  * when their own homepage is infected, we can get them somewhere safe.
  2151.  */
  2152. function getMeOutOfHere() {
  2153.   // Get the start page from the *default* pref branch, not the user's
  2154.   var prefs = Cc["@mozilla.org/preferences-service;1"]
  2155.              .getService(Ci.nsIPrefService).getDefaultBranch(null);
  2156.   var url = "about:blank";
  2157.   try {
  2158.     url = prefs.getComplexValue("browser.startup.homepage",
  2159.                                 Ci.nsIPrefLocalizedString).data;
  2160.     // If url is a pipe-delimited set of pages, just take the first one.
  2161.     if (url.indexOf("|") != -1)
  2162.       url = url.split("|")[0];
  2163.   } catch(e) {
  2164.     Components.utils.reportError("Couldn't get homepage pref: " + e);
  2165.   }
  2166.   content.location = url;
  2167. }
  2168.  
  2169. function BrowserFullScreen()
  2170. {
  2171.   window.fullScreen = !window.fullScreen;
  2172. }
  2173.  
  2174. function onFullScreen()
  2175. {
  2176.   FullScreen.toggle();
  2177. }
  2178.  
  2179. function getWebNavigation()
  2180. {
  2181.   try {
  2182.     return gBrowser.webNavigation;
  2183.   } catch (e) {
  2184.     return null;
  2185.   }
  2186. }
  2187.  
  2188. function BrowserReloadWithFlags(reloadFlags) {
  2189.   /* First, we'll try to use the session history object to reload so
  2190.    * that framesets are handled properly. If we're in a special
  2191.    * window (such as view-source) that has no session history, fall
  2192.    * back on using the web navigation's reload method.
  2193.    */
  2194.  
  2195.   var webNav = getWebNavigation();
  2196.   try {
  2197.     var sh = webNav.sessionHistory;
  2198.     if (sh)
  2199.       webNav = sh.QueryInterface(nsIWebNavigation);
  2200.   } catch (e) {
  2201.   }
  2202.  
  2203.   try {
  2204.     webNav.reload(reloadFlags);
  2205.   } catch (e) {
  2206.   }
  2207. }
  2208.  
  2209. function toggleAffectedChrome(aHide)
  2210. {
  2211.   // chrome to toggle includes:
  2212.   //   (*) menubar
  2213.   //   (*) navigation bar
  2214.   //   (*) bookmarks toolbar
  2215.   //   (*) tabstrip
  2216.   //   (*) browser messages
  2217.   //   (*) sidebar
  2218.   //   (*) find bar
  2219.   //   (*) statusbar
  2220.  
  2221.   gNavToolbox.hidden = aHide;
  2222.   if (aHide)
  2223.   {
  2224.     gChromeState = {};
  2225.     var sidebar = document.getElementById("sidebar-box");
  2226.     gChromeState.sidebarOpen = !sidebar.hidden;
  2227.     gSidebarCommand = sidebar.getAttribute("sidebarcommand");
  2228.  
  2229.     gChromeState.hadTabStrip = gBrowser.getStripVisibility();
  2230.     gBrowser.setStripVisibilityTo(false);
  2231.  
  2232.     var notificationBox = gBrowser.getNotificationBox();
  2233.     gChromeState.notificationsOpen = !notificationBox.notificationsHidden;
  2234.     notificationBox.notificationsHidden = aHide;
  2235.  
  2236.     document.getElementById("sidebar").setAttribute("src", "about:blank");
  2237.     var statusbar = document.getElementById("status-bar");
  2238.     gChromeState.statusbarOpen = !statusbar.hidden;
  2239.     statusbar.hidden = aHide;
  2240.  
  2241.     gChromeState.findOpen = !gFindBar.hidden;
  2242.     gFindBar.close();
  2243.   }
  2244.   else {
  2245.     if (gChromeState.hadTabStrip) {
  2246.       gBrowser.setStripVisibilityTo(true);
  2247.     }
  2248.  
  2249.     if (gChromeState.notificationsOpen) {
  2250.       gBrowser.getNotificationBox().notificationsHidden = aHide;
  2251.     }
  2252.  
  2253.     if (gChromeState.statusbarOpen) {
  2254.       var statusbar = document.getElementById("status-bar");
  2255.       statusbar.hidden = aHide;
  2256.     }
  2257.  
  2258.     if (gChromeState.findOpen)
  2259.       gFindBar.open();
  2260.   }
  2261.  
  2262.   if (gChromeState.sidebarOpen)
  2263.     toggleSidebar(gSidebarCommand);
  2264. }
  2265.  
  2266. function onEnterPrintPreview()
  2267. {
  2268.   gInPrintPreviewMode = true;
  2269.   toggleAffectedChrome(true);
  2270. }
  2271.  
  2272. function onExitPrintPreview()
  2273. {
  2274.   // restore chrome to original state
  2275.   gInPrintPreviewMode = false;
  2276.   FullZoom.setSettingValue();
  2277.   toggleAffectedChrome(false);
  2278. }
  2279.  
  2280. function getPPBrowser()
  2281. {
  2282.   return gBrowser;
  2283. }
  2284.  
  2285. function getMarkupDocumentViewer()
  2286. {
  2287.   return gBrowser.markupDocumentViewer;
  2288. }
  2289.  
  2290. /**
  2291.  * Content area tooltip.
  2292.  * XXX - this must move into XBL binding/equiv! Do not want to pollute
  2293.  *       browser.js with functionality that can be encapsulated into
  2294.  *       browser widget. TEMPORARY!
  2295.  *
  2296.  * NOTE: Any changes to this routine need to be mirrored in ChromeListener::FindTitleText()
  2297.  *       (located in mozilla/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp)
  2298.  *       which performs the same function, but for embedded clients that
  2299.  *       don't use a XUL/JS layer. It is important that the logic of
  2300.  *       these two routines be kept more or less in sync.
  2301.  *       (pinkerton)
  2302.  **/
  2303. function FillInHTMLTooltip(tipElement)
  2304. {
  2305.   var retVal = false;
  2306.   if (tipElement.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul")
  2307.     return retVal;
  2308.  
  2309.   const XLinkNS = "http://www.w3.org/1999/xlink";
  2310.  
  2311.  
  2312.   var titleText = null;
  2313.   var XLinkTitleText = null;
  2314.   var direction = tipElement.ownerDocument.dir;
  2315.  
  2316.   while (!titleText && !XLinkTitleText && tipElement) {
  2317.     if (tipElement.nodeType == Node.ELEMENT_NODE) {
  2318.       titleText = tipElement.getAttribute("title");
  2319.       XLinkTitleText = tipElement.getAttributeNS(XLinkNS, "title");
  2320.       var defView = tipElement.ownerDocument.defaultView;
  2321.       // XXX Work around bug 350679:
  2322.       // "Tooltips can be fired in documents with no view".
  2323.       if (!defView)
  2324.         return retVal;
  2325.       direction = defView.getComputedStyle(tipElement, "")
  2326.         .getPropertyValue("direction");
  2327.     }
  2328.     tipElement = tipElement.parentNode;
  2329.   }
  2330.  
  2331.   var tipNode = document.getElementById("aHTMLTooltip");
  2332.   tipNode.style.direction = direction;
  2333.   
  2334.   for each (var t in [titleText, XLinkTitleText]) {
  2335.     if (t && /\S/.test(t)) {
  2336.  
  2337.       // Per HTML 4.01 6.2 (CDATA section), literal CRs and tabs should be
  2338.       // replaced with spaces, and LFs should be removed entirely.
  2339.       // XXX Bug 322270: We don't preserve the result of entities like  ,
  2340.       // which should result in a line break in the tooltip, because we can't
  2341.       // distinguish that from a literal character in the source by this point.
  2342.       t = t.replace(/[\r\t]/g, ' ');
  2343.       t = t.replace(/\n/g, '');
  2344.  
  2345.       tipNode.setAttribute("label", t);
  2346.       retVal = true;
  2347.     }
  2348.   }
  2349.  
  2350.   return retVal;
  2351. }
  2352.  
  2353. var proxyIconDNDObserver = {
  2354.   onDragStart: function (aEvent, aXferData, aDragAction)
  2355.     {
  2356.       var value = content.location.href;
  2357.       var urlString = value + "\n" + content.document.title;
  2358.       var htmlString = "<a href=\"" + value + "\">" + value + "</a>";
  2359.  
  2360.       aXferData.data = new TransferData();
  2361.       aXferData.data.addDataForFlavour("text/x-moz-url", urlString);
  2362.       aXferData.data.addDataForFlavour("text/unicode", value);
  2363.       aXferData.data.addDataForFlavour("text/html", htmlString);
  2364.  
  2365.       // we're copying the URL from the proxy icon, not moving
  2366.       // we specify all of them though, because d&d sucks and OS's
  2367.       // get confused if they don't get the one they want
  2368.       aDragAction.action =
  2369.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_COPY |
  2370.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_MOVE |
  2371.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  2372.     }
  2373. }
  2374.  
  2375. var homeButtonObserver = {
  2376.   onDrop: function (aEvent, aXferData, aDragSession)
  2377.     {
  2378.       var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
  2379.       setTimeout(openHomeDialog, 0, url);
  2380.     },
  2381.  
  2382.   onDragOver: function (aEvent, aFlavour, aDragSession)
  2383.     {
  2384.       var statusTextFld = document.getElementById("statusbar-display");
  2385.       statusTextFld.label = gNavigatorBundle.getString("droponhomebutton");
  2386.       aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  2387.     },
  2388.  
  2389.   onDragExit: function (aEvent, aDragSession)
  2390.     {
  2391.       var statusTextFld = document.getElementById("statusbar-display");
  2392.       statusTextFld.label = "";
  2393.     },
  2394.  
  2395.   getSupportedFlavours: function ()
  2396.     {
  2397.       var flavourSet = new FlavourSet();
  2398.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2399.       flavourSet.appendFlavour("text/x-moz-url");
  2400.       flavourSet.appendFlavour("text/unicode");
  2401.       flavourSet.appendFlavour("text/x-moz-text-internal");  // for tabs
  2402.       return flavourSet;
  2403.     }
  2404. }
  2405.  
  2406. function openHomeDialog(aURL)
  2407. {
  2408.   var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  2409.   var promptTitle = gNavigatorBundle.getString("droponhometitle");
  2410.   var promptMsg   = gNavigatorBundle.getString("droponhomemsg");
  2411.   var pressedVal  = promptService.confirmEx(window, promptTitle, promptMsg,
  2412.                           promptService.STD_YES_NO_BUTTONS,
  2413.                           null, null, null, null, {value:0});
  2414.  
  2415.   if (pressedVal == 0) {
  2416.     try {
  2417.       var str = Components.classes["@mozilla.org/supports-string;1"]
  2418.                           .createInstance(Components.interfaces.nsISupportsString);
  2419.       str.data = aURL;
  2420.       gPrefService.setComplexValue("browser.startup.homepage",
  2421.                                    Components.interfaces.nsISupportsString, str);
  2422.       var homeButton = document.getElementById("home-button");
  2423.       homeButton.setAttribute("tooltiptext", aURL);
  2424.     } catch (ex) {
  2425.       dump("Failed to set the home page.\n"+ex+"\n");
  2426.     }
  2427.   }
  2428. }
  2429.  
  2430. var bookmarksButtonObserver = {
  2431.   onDrop: function (aEvent, aXferData, aDragSession)
  2432.   {
  2433.     var split = aXferData.data.split("\n");
  2434.     var url = split[0];
  2435.     if (url != aXferData.data)  // do nothing if it's not a valid URL
  2436.       PlacesUIUtils.showMinimalAddBookmarkUI(makeURI(url), split[1]);
  2437.   },
  2438.  
  2439.   onDragOver: function (aEvent, aFlavour, aDragSession)
  2440.   {
  2441.     var statusTextFld = document.getElementById("statusbar-display");
  2442.     statusTextFld.label = gNavigatorBundle.getString("droponbookmarksbutton");
  2443.     aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  2444.   },
  2445.  
  2446.   onDragExit: function (aEvent, aDragSession)
  2447.   {
  2448.     var statusTextFld = document.getElementById("statusbar-display");
  2449.     statusTextFld.label = "";
  2450.   },
  2451.  
  2452.   getSupportedFlavours: function ()
  2453.   {
  2454.     var flavourSet = new FlavourSet();
  2455.     flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2456.     flavourSet.appendFlavour("text/x-moz-url");
  2457.     flavourSet.appendFlavour("text/unicode");
  2458.     return flavourSet;
  2459.   }
  2460. }
  2461.  
  2462. var newTabButtonObserver = {
  2463.   onDragOver: function(aEvent, aFlavour, aDragSession) {
  2464.     var statusTextFld = document.getElementById("statusbar-display");
  2465.     statusTextFld.label = gNavigatorBundle.getString("droponnewtabbutton");
  2466.     aEvent.target.setAttribute("dragover", "true");
  2467.     return true;
  2468.   },
  2469.   onDragExit: function (aEvent, aDragSession) {
  2470.     var statusTextFld = document.getElementById("statusbar-display");
  2471.     statusTextFld.label = "";
  2472.     aEvent.target.removeAttribute("dragover");
  2473.   },
  2474.   onDrop: function (aEvent, aXferData, aDragSession) {
  2475.     var xferData = aXferData.data.split("\n");
  2476.     var draggedText = xferData[0] || xferData[1];
  2477.     var postData = {};
  2478.     var url = getShortcutOrURI(draggedText, postData);
  2479.     if (url) {
  2480.       nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  2481.       // allow third-party services to fixup this URL
  2482.       openNewTabWith(url, null, postData.value, aEvent, true);
  2483.     }
  2484.   },
  2485.   getSupportedFlavours: function () {
  2486.     var flavourSet = new FlavourSet();
  2487.     flavourSet.appendFlavour("text/unicode");
  2488.     flavourSet.appendFlavour("text/x-moz-url");
  2489.     flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2490.     flavourSet.appendFlavour("text/x-moz-text-internal"); // for tabs
  2491.     return flavourSet;
  2492.   }
  2493. }
  2494.  
  2495. var newWindowButtonObserver = {
  2496.   onDragOver: function(aEvent, aFlavour, aDragSession)
  2497.     {
  2498.       var statusTextFld = document.getElementById("statusbar-display");
  2499.       statusTextFld.label = gNavigatorBundle.getString("droponnewwindowbutton");
  2500.       aEvent.target.setAttribute("dragover", "true");
  2501.       return true;
  2502.     },
  2503.   onDragExit: function (aEvent, aDragSession)
  2504.     {
  2505.       var statusTextFld = document.getElementById("statusbar-display");
  2506.       statusTextFld.label = "";
  2507.       aEvent.target.removeAttribute("dragover");
  2508.     },
  2509.   onDrop: function (aEvent, aXferData, aDragSession)
  2510.     {
  2511.       var xferData = aXferData.data.split("\n");
  2512.       var draggedText = xferData[0] || xferData[1];
  2513.       var postData = {};
  2514.       var url = getShortcutOrURI(draggedText, postData);
  2515.       if (url) {
  2516.         nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  2517.         // allow third-party services to fixup this URL
  2518.         openNewWindowWith(url, null, postData.value, true);
  2519.       }
  2520.     },
  2521.   getSupportedFlavours: function ()
  2522.     {
  2523.       var flavourSet = new FlavourSet();
  2524.       flavourSet.appendFlavour("text/unicode");
  2525.       flavourSet.appendFlavour("text/x-moz-url");
  2526.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2527.       flavourSet.appendFlavour("text/x-moz-text-internal");  // for tabs
  2528.       return flavourSet;
  2529.     }
  2530. }
  2531.  
  2532. var DownloadsButtonDNDObserver = {
  2533.   /////////////////////////////////////////////////////////////////////////////
  2534.   // nsDragAndDrop
  2535.   onDragOver: function (aEvent, aFlavour, aDragSession)
  2536.   {
  2537.     var statusTextFld = document.getElementById("statusbar-display");
  2538.     statusTextFld.label = gNavigatorBundle.getString("dropondownloadsbutton");
  2539.     aDragSession.canDrop = (aFlavour.contentType == "text/x-moz-url" ||
  2540.                             aFlavour.contentType == "text/unicode");
  2541.   },
  2542.  
  2543.   onDragExit: function (aEvent, aDragSession)
  2544.   {
  2545.     var statusTextFld = document.getElementById("statusbar-display");
  2546.     statusTextFld.label = "";
  2547.   },
  2548.  
  2549.   onDrop: function (aEvent, aXferData, aDragSession)
  2550.   {
  2551.     var split = aXferData.data.split("\n");
  2552.     var url = split[0];
  2553.     if (url != aXferData.data) {  //do nothing, not a valid URL
  2554.       nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  2555.  
  2556.       var name = split[1];
  2557.       saveURL(url, name, null, true, true);
  2558.     }
  2559.   },
  2560.   getSupportedFlavours: function ()
  2561.   {
  2562.     var flavourSet = new FlavourSet();
  2563.     flavourSet.appendFlavour("text/x-moz-url");
  2564.     flavourSet.appendFlavour("text/unicode");
  2565.     return flavourSet;
  2566.   }
  2567. }
  2568.  
  2569. const DOMLinkHandler = {
  2570.   handleEvent: function (event) {
  2571.     switch (event.type) {
  2572.       case "DOMLinkAdded":
  2573.         this.onLinkAdded(event);
  2574.         break;
  2575.     }
  2576.   },
  2577.   onLinkAdded: function (event) {
  2578.     var link = event.originalTarget;
  2579.     var rel = link.rel && link.rel.toLowerCase();
  2580.     if (!link || !link.ownerDocument || !rel || !link.href)
  2581.       return;
  2582.  
  2583.     var feedAdded = false;
  2584.     var iconAdded = false;
  2585.     var searchAdded = false;
  2586.     var relStrings = rel.split(/\s+/);
  2587.     var rels = {};
  2588.     for (let i = 0; i < relStrings.length; i++)
  2589.       rels[relStrings[i]] = true;
  2590.  
  2591.     for (let relVal in rels) {
  2592.       switch (relVal) {
  2593.         case "feed":
  2594.         case "alternate":
  2595.           if (!feedAdded) {
  2596.             if (!rels.feed && rels.alternate && rels.stylesheet)
  2597.               break;
  2598.  
  2599.             if (isValidFeed(link, link.ownerDocument.nodePrincipal, rels.feed)) {
  2600.               FeedHandler.addFeed(link, link.ownerDocument);
  2601.               feedAdded = true;
  2602.             }
  2603.           }
  2604.           break;
  2605.         case "icon":
  2606.           if (!iconAdded) {
  2607.             if (!gPrefService.getBoolPref("browser.chrome.site_icons"))
  2608.               break;
  2609.  
  2610.             var targetDoc = link.ownerDocument;
  2611.             var ios = Cc["@mozilla.org/network/io-service;1"].
  2612.                       getService(Ci.nsIIOService);
  2613.             var uri = ios.newURI(link.href, targetDoc.characterSet, null);
  2614.  
  2615.             if (gBrowser.isFailedIcon(uri))
  2616.               break;
  2617.  
  2618.             // Verify that the load of this icon is legal.
  2619.             // error pages can load their favicon, to be on the safe side,
  2620.             // only allow chrome:// favicons
  2621.             const aboutNeterr = /^about:neterror\?/;
  2622.             const aboutBlocked = /^about:blocked\?/;
  2623.             const aboutCert = /^about:certerror\?/;
  2624.             if (!(aboutNeterr.test(targetDoc.documentURI) ||
  2625.                   aboutBlocked.test(targetDoc.documentURI) ||
  2626.                   aboutCert.test(targetDoc.documentURI)) ||
  2627.                 !uri.schemeIs("chrome")) {
  2628.               var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].
  2629.                         getService(Ci.nsIScriptSecurityManager);
  2630.               try {
  2631.                 ssm.checkLoadURIWithPrincipal(targetDoc.nodePrincipal, uri,
  2632.                                               Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT);
  2633.               } catch(e) {
  2634.                 break;
  2635.               }
  2636.             }
  2637.  
  2638.             try {
  2639.               var contentPolicy = Cc["@mozilla.org/layout/content-policy;1"].
  2640.                                   getService(Ci.nsIContentPolicy);
  2641.             } catch(e) {
  2642.               break; // Refuse to load if we can't do a security check.
  2643.             }
  2644.  
  2645.             // Security says okay, now ask content policy
  2646.             if (contentPolicy.shouldLoad(Ci.nsIContentPolicy.TYPE_IMAGE,
  2647.                                          uri, targetDoc.documentURIObject,
  2648.                                          link, link.type, null)
  2649.                                          != Ci.nsIContentPolicy.ACCEPT)
  2650.               break;
  2651.  
  2652.             var browserIndex = gBrowser.getBrowserIndexForDocument(targetDoc);
  2653.             // no browser? no favicon.
  2654.             if (browserIndex == -1)
  2655.               break;
  2656.  
  2657.             var tab = gBrowser.mTabContainer.childNodes[browserIndex];
  2658.             gBrowser.setIcon(tab, link.href);
  2659.             iconAdded = true;
  2660.           }
  2661.           break;
  2662.         case "search":
  2663.           if (!searchAdded) {
  2664.             var type = link.type && link.type.toLowerCase();
  2665.             type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
  2666.  
  2667.             if (type == "application/opensearchdescription+xml" && link.title &&
  2668.                 /^(?:https?|ftp):/i.test(link.href)) {
  2669.               var engine = { title: link.title, href: link.href };
  2670.               BrowserSearch.addEngine(engine, link.ownerDocument);
  2671.               searchAdded = true;
  2672.             }
  2673.           }
  2674.           break;
  2675.       }
  2676.     }
  2677.   }
  2678. }
  2679.  
  2680. const BrowserSearch = {
  2681.   addEngine: function(engine, targetDoc) {
  2682.     if (!this.searchBar)
  2683.       return;
  2684.  
  2685.     var browser = gBrowser.getBrowserForDocument(targetDoc);
  2686.     // ignore search engines from subframes (see bug 479408)
  2687.     if (!browser)
  2688.       return;
  2689.  
  2690.     // Check to see whether we've already added an engine with this title
  2691.     if (browser.engines) {
  2692.       if (browser.engines.some(function (e) e.title == engine.title))
  2693.         return;
  2694.     }
  2695.  
  2696.     // Append the URI and an appropriate title to the browser data.
  2697.     // Use documentURIObject in the check for shouldLoadFavIcon so that we
  2698.     // do the right thing with about:-style error pages.  Bug 453442
  2699.     var iconURL = null;
  2700.     if (gBrowser.shouldLoadFavIcon(targetDoc.documentURIObject))
  2701.       iconURL = targetDoc.documentURIObject.prePath + "/favicon.ico";
  2702.  
  2703.     var hidden = false;
  2704.     // If this engine (identified by title) is already in the list, add it
  2705.     // to the list of hidden engines rather than to the main list.
  2706.     // XXX This will need to be changed when engines are identified by URL;
  2707.     // see bug 335102.
  2708.     var searchService = Cc["@mozilla.org/browser/search-service;1"].
  2709.                         getService(Ci.nsIBrowserSearchService);
  2710.     if (searchService.getEngineByName(engine.title))
  2711.       hidden = true;
  2712.  
  2713.     var engines = (hidden ? browser.hiddenEngines : browser.engines) || [];
  2714.  
  2715.     engines.push({ uri: engine.href,
  2716.                    title: engine.title,
  2717.                    icon: iconURL });
  2718.  
  2719.     if (hidden)
  2720.       browser.hiddenEngines = engines;
  2721.     else {
  2722.       browser.engines = engines;
  2723.       if (browser == gBrowser.mCurrentBrowser)
  2724.         this.updateSearchButton();
  2725.     }
  2726.   },
  2727.  
  2728.   /**
  2729.    * Update the browser UI to show whether or not additional engines are 
  2730.    * available when a page is loaded or the user switches tabs to a page that 
  2731.    * has search engines.
  2732.    */
  2733.   updateSearchButton: function() {
  2734.     var searchBar = this.searchBar;
  2735.     
  2736.     // The search bar binding might not be applied even though the element is
  2737.     // in the document (e.g. when the navigation toolbar is hidden), so check
  2738.     // for .searchButton specifically.
  2739.     if (!searchBar || !searchBar.searchButton)
  2740.       return;
  2741.  
  2742.     var engines = gBrowser.mCurrentBrowser.engines;
  2743.     if (engines && engines.length > 0)
  2744.       searchBar.searchButton.setAttribute("addengines", "true");
  2745.     else
  2746.       searchBar.searchButton.removeAttribute("addengines");
  2747.   },
  2748.  
  2749.   /**
  2750.    * Gives focus to the search bar, if it is present on the toolbar, or loads
  2751.    * the default engine's search form otherwise. For Mac, opens a new window
  2752.    * or focuses an existing window, if necessary.
  2753.    */
  2754.   webSearch: function BrowserSearch_webSearch() {
  2755. //@line 3096 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  2756.     if (window.fullScreen)
  2757.       FullScreen.mouseoverToggle(true);
  2758.  
  2759.     var searchBar = this.searchBar;
  2760.     if (isElementVisible(searchBar)) {
  2761.       searchBar.select();
  2762.       searchBar.focus();
  2763.     } else {
  2764.       var ss = Cc["@mozilla.org/browser/search-service;1"].
  2765.                getService(Ci.nsIBrowserSearchService);
  2766.       var searchForm = ss.defaultEngine.searchForm;
  2767.       loadURI(searchForm, null, null, false);
  2768.     }
  2769.   },
  2770.  
  2771.   /**
  2772.    * Loads a search results page, given a set of search terms. Uses the current
  2773.    * engine if the search bar is visible, or the default engine otherwise.
  2774.    *
  2775.    * @param searchText
  2776.    *        The search terms to use for the search.
  2777.    *
  2778.    * @param useNewTab
  2779.    *        Boolean indicating whether or not the search should load in a new
  2780.    *        tab.
  2781.    */
  2782.   loadSearch: function BrowserSearch_search(searchText, useNewTab) {
  2783.     var ss = Cc["@mozilla.org/browser/search-service;1"].
  2784.              getService(Ci.nsIBrowserSearchService);
  2785.     var engine;
  2786.   
  2787.     // If the search bar is visible, use the current engine, otherwise, fall
  2788.     // back to the default engine.
  2789.     if (isElementVisible(this.searchBar))
  2790.       engine = ss.currentEngine;
  2791.     else
  2792.       engine = ss.defaultEngine;
  2793.   
  2794.     var submission = engine.getSubmission(searchText, null); // HTML response
  2795.  
  2796.     // getSubmission can return null if the engine doesn't have a URL
  2797.     // with a text/html response type.  This is unlikely (since
  2798.     // SearchService._addEngineToStore() should fail for such an engine),
  2799.     // but let's be on the safe side.
  2800.     if (!submission)
  2801.       return;
  2802.   
  2803.     if (useNewTab) {
  2804.       gBrowser.loadOneTab(submission.uri.spec, null, null,
  2805.                           submission.postData, null, false);
  2806.     } else
  2807.       loadURI(submission.uri.spec, null, submission.postData, false);
  2808.   },
  2809.  
  2810.   /**
  2811.    * Returns the search bar element if it is present in the toolbar, null otherwise.
  2812.    */
  2813.   get searchBar() {
  2814.     return document.getElementById("searchbar");
  2815.   },
  2816.  
  2817.   loadAddEngines: function BrowserSearch_loadAddEngines() {
  2818.     var newWindowPref = gPrefService.getIntPref("browser.link.open_newwindow");
  2819.     var where = newWindowPref == 3 ? "tab" : "window";
  2820.     var regionBundle = document.getElementById("bundle_browser_region");
  2821.     var searchEnginesURL = formatURL("browser.search.searchEnginesURL", true);
  2822.     openUILinkIn(searchEnginesURL, where);
  2823.   }
  2824. }
  2825.  
  2826. function FillHistoryMenu(aParent) {
  2827.   // Remove old entries if any
  2828.   var children = aParent.childNodes;
  2829.   for (var i = children.length - 1; i >= 0; --i) {
  2830.     if (children[i].hasAttribute("index"))
  2831.       aParent.removeChild(children[i]);
  2832.   }
  2833.  
  2834.   var webNav = getWebNavigation();
  2835.   var sessionHistory = webNav.sessionHistory;
  2836.   var bundle_browser = document.getElementById("bundle_browser");
  2837.  
  2838.   var count = sessionHistory.count;
  2839.   var index = sessionHistory.index;
  2840.   var end;
  2841.  
  2842.   if (count <= 1) // don't display the popup for a single item
  2843.     return false;
  2844.  
  2845.   var half_length = Math.floor(MAX_HISTORY_MENU_ITEMS / 2);
  2846.   var start = Math.max(index - half_length, 0);
  2847.   end = Math.min(start == 0 ? MAX_HISTORY_MENU_ITEMS : index + half_length + 1, count);
  2848.   if (end == count)
  2849.     start = Math.max(count - MAX_HISTORY_MENU_ITEMS, 0);
  2850.  
  2851.   var tooltipBack = bundle_browser.getString("tabHistory.goBack");
  2852.   var tooltipCurrent = bundle_browser.getString("tabHistory.current");
  2853.   var tooltipForward = bundle_browser.getString("tabHistory.goForward");
  2854.  
  2855.   for (var j = end - 1; j >= start; j--) {
  2856.     let item = document.createElement("menuitem");
  2857.     let entry = sessionHistory.getEntryAtIndex(j, false);
  2858.  
  2859.     item.setAttribute("label", entry.title || entry.URI.spec);
  2860.     item.setAttribute("index", j);
  2861.  
  2862.     if (j != index) {
  2863.       try {
  2864.         let iconURL = Cc["@mozilla.org/browser/favicon-service;1"]
  2865.                          .getService(Ci.nsIFaviconService)
  2866.                          .getFaviconForPage(entry.URI).spec;
  2867.         item.style.listStyleImage = "url(" + iconURL + ")";
  2868.       } catch (ex) {}
  2869.     }
  2870.  
  2871.     if (j < index) {
  2872.       item.className = "unified-nav-back menuitem-iconic";
  2873.       item.setAttribute("tooltiptext", tooltipBack);
  2874.     } else if (j == index) {
  2875.       item.setAttribute("type", "radio");
  2876.       item.setAttribute("checked", "true");
  2877.       item.className = "unified-nav-current";
  2878.       item.setAttribute("tooltiptext", tooltipCurrent);
  2879.     } else {
  2880.       item.className = "unified-nav-forward menuitem-iconic";
  2881.       item.setAttribute("tooltiptext", tooltipForward);
  2882.     }
  2883.  
  2884.     aParent.appendChild(item);
  2885.   }
  2886.   return true;
  2887. }
  2888.  
  2889. function addToUrlbarHistory(aUrlToAdd) {
  2890.   if (aUrlToAdd &&
  2891.       aUrlToAdd.indexOf(" ") == -1 &&
  2892.       !/[\x00-\x1F]/.test(aUrlToAdd))
  2893.     PlacesUIUtils.markPageAsTyped(aUrlToAdd);
  2894. }
  2895.  
  2896. function toJavaScriptConsole()
  2897. {
  2898.   toOpenWindowByType("global:console", "chrome://global/content/console.xul");
  2899. }
  2900.  
  2901. function BrowserDownloadsUI()
  2902. {
  2903.   Cc["@mozilla.org/download-manager-ui;1"].
  2904.   getService(Ci.nsIDownloadManagerUI).show(window);
  2905. }
  2906.  
  2907. function toOpenWindowByType(inType, uri, features)
  2908. {
  2909.   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  2910.   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  2911.   var topWindow = windowManagerInterface.getMostRecentWindow(inType);
  2912.  
  2913.   if (topWindow)
  2914.     topWindow.focus();
  2915.   else if (features)
  2916.     window.open(uri, "_blank", features);
  2917.   else
  2918.     window.open(uri, "_blank", "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar");
  2919. }
  2920.  
  2921. function toOpenDialogByTypeAndUrl(inType, relatedUrl, windowUri, features, extraArgument)
  2922. {
  2923.   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  2924.   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  2925.   var windows = windowManagerInterface.getEnumerator(inType);
  2926.  
  2927.   // Check for windows matching the url
  2928.   while (windows.hasMoreElements()) {
  2929.     var currentWindow = windows.getNext();
  2930.     if (currentWindow.document.documentElement.getAttribute("relatedUrl") == relatedUrl) {
  2931.         currentWindow.focus();
  2932.         return;
  2933.     }
  2934.   }
  2935.  
  2936.   // We didn't find a matching window, so open a new one.
  2937.   if (features)
  2938.     return window.openDialog(windowUri, "_blank", features, extraArgument);
  2939.  
  2940.   return window.openDialog(windowUri, "_blank", "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar", extraArgument);
  2941. }
  2942.  
  2943. function OpenBrowserWindow()
  2944. {
  2945.   var charsetArg = new String();
  2946.   var handler = Components.classes["@mozilla.org/browser/clh;1"]
  2947.                           .getService(Components.interfaces.nsIBrowserHandler);
  2948.   var defaultArgs = handler.defaultArgs;
  2949.   var wintype = document.documentElement.getAttribute('windowtype');
  2950.  
  2951.   // if and only if the current window is a browser window and it has a document with a character
  2952.   // set, then extract the current charset menu setting from the current document and use it to
  2953.   // initialize the new browser window...
  2954.   var win;
  2955.   if (window && (wintype == "navigator:browser") && window.content && window.content.document)
  2956.   {
  2957.     var DocCharset = window.content.document.characterSet;
  2958.     charsetArg = "charset="+DocCharset;
  2959.  
  2960.     //we should "inherit" the charset menu setting in a new window
  2961.     win = window.openDialog("chrome://browser/content/", "_blank", "chrome,all,dialog=no", defaultArgs, charsetArg);
  2962.   }
  2963.   else // forget about the charset information.
  2964.   {
  2965.     win = window.openDialog("chrome://browser/content/", "_blank", "chrome,all,dialog=no", defaultArgs);
  2966.   }
  2967.  
  2968.   return win;
  2969. }
  2970.  
  2971. function BrowserCustomizeToolbar()
  2972. {
  2973.   // Disable the toolbar context menu items
  2974.   var menubar = document.getElementById("main-menubar");
  2975.   for (var i = 0; i < menubar.childNodes.length; ++i)
  2976.     menubar.childNodes[i].setAttribute("disabled", true);
  2977.  
  2978.   var cmd = document.getElementById("cmd_CustomizeToolbars");
  2979.   cmd.setAttribute("disabled", "true");
  2980.  
  2981.   var splitter = document.getElementById("urlbar-search-splitter");
  2982.   if (splitter)
  2983.     splitter.parentNode.removeChild(splitter);
  2984.  
  2985.   var customizeURL = "chrome://global/content/customizeToolbar.xul";
  2986. //@line 3348 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  2987.   window.openDialog(customizeURL,
  2988.                     "CustomizeToolbar",
  2989.                     "chrome,titlebar,toolbar,location,resizable,dependent",
  2990.                     gNavToolbox);
  2991. //@line 3353 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  2992. }
  2993.  
  2994. function BrowserToolboxCustomizeDone(aToolboxChanged) {
  2995. //@line 3360 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  2996.  
  2997.   // Update global UI elements that may have been added or removed
  2998.   if (aToolboxChanged) {
  2999.     gURLBar = document.getElementById("urlbar");
  3000.     if (gURLBar)
  3001.       gURLBar.emptyText = gURLBarEmptyText.value;
  3002.  
  3003.     gProxyFavIcon = document.getElementById("page-proxy-favicon");
  3004.     gHomeButton.updateTooltip();
  3005.     gIdentityHandler._cacheElements();
  3006.     window.XULBrowserWindow.init();
  3007.  
  3008.     var backForwardDropmarker = document.getElementById("back-forward-dropmarker");
  3009.     if (backForwardDropmarker)
  3010.       backForwardDropmarker.disabled =
  3011.         document.getElementById('Browser:Back').hasAttribute('disabled') &&
  3012.         document.getElementById('Browser:Forward').hasAttribute('disabled');
  3013.  
  3014.     // support downgrading to Firefox 2.0
  3015.     var navBar = document.getElementById("nav-bar");
  3016.     navBar.setAttribute("currentset",
  3017.                         navBar.getAttribute("currentset")
  3018.                               .replace("unified-back-forward-button",
  3019.                                 "unified-back-forward-button,back-button,forward-button"));
  3020.     document.persist(navBar.id, "currentset");
  3021.  
  3022. //@line 3387 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3023.     updateEditUIVisibility();
  3024. //@line 3389 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3025.   }
  3026.  
  3027.   UpdateUrlbarSearchSplitterState();
  3028.  
  3029.   gHomeButton.updatePersonalToolbarStyle();
  3030.  
  3031.   // Update the urlbar
  3032.   if (gURLBar) {
  3033.     URLBarSetURI();
  3034.     XULBrowserWindow.asyncUpdateUI();
  3035.     PlacesStarButton.updateState();
  3036.   }
  3037.  
  3038.   // Re-enable parts of the UI we disabled during the dialog
  3039.   var menubar = document.getElementById("main-menubar");
  3040.   for (var i = 0; i < menubar.childNodes.length; ++i)
  3041.     menubar.childNodes[i].setAttribute("disabled", false);
  3042.   var cmd = document.getElementById("cmd_CustomizeToolbars");
  3043.   cmd.removeAttribute("disabled");
  3044.  
  3045.   // XXXmano bug 287105: wallpaper to bug 309953,
  3046.   // the reload button isn't in sync with the reload command.
  3047.   var reloadButton = document.getElementById("reload-button");
  3048.   if (reloadButton) {
  3049.     reloadButton.disabled =
  3050.       document.getElementById("Browser:Reload").getAttribute("disabled") == "true";
  3051.   }
  3052.   //bug 440702: the back and forward buttons also suffer from bug 309953.
  3053.   var backButton = document.getElementById("back-button");
  3054.   if (backButton) {
  3055.     backButton.disabled =
  3056.       document.getElementById("Browser:Back").getAttribute("disabled") == "true";
  3057.   }
  3058.   var forwardButton = document.getElementById("forward-button");
  3059.   if (forwardButton) {
  3060.     forwardButton.disabled =
  3061.       document.getElementById("Browser:Forward").getAttribute("disabled") == "true";
  3062.   }
  3063.  
  3064. //@line 3433 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3065.  
  3066. //@line 3435 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3067.   // XXX Shouldn't have to do this, but I do
  3068.   window.focus();
  3069. //@line 3438 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3070. }
  3071.  
  3072. function BrowserToolboxCustomizeChange() {
  3073.   gHomeButton.updatePersonalToolbarStyle();
  3074. }
  3075.  
  3076. /**
  3077.  * Update the global flag that tracks whether or not any edit UI (the Edit menu,
  3078.  * edit-related items in the context menu, and edit-related toolbar buttons
  3079.  * is visible, then update the edit commands' enabled state accordingly.  We use
  3080.  * this flag to skip updating the edit commands on focus or selection changes
  3081.  * when no UI is visible to improve performance (including pageload performance,
  3082.  * since focus changes when you load a new page).
  3083.  *
  3084.  * If UI is visible, we use goUpdateGlobalEditMenuItems to set the commands'
  3085.  * enabled state so the UI will reflect it appropriately.
  3086.  * 
  3087.  * If the UI isn't visible, we enable all edit commands so keyboard shortcuts
  3088.  * still work and just lazily disable them as needed when the user presses a
  3089.  * shortcut.
  3090.  *
  3091.  * This doesn't work on Mac, since Mac menus flash when users press their
  3092.  * keyboard shortcuts, so edit UI is essentially always visible on the Mac,
  3093.  * and we need to always update the edit commands.  Thus on Mac this function
  3094.  * is a no op.
  3095.  */
  3096. function updateEditUIVisibility()
  3097. {
  3098. //@line 3467 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3099.   let editMenuPopupState = document.getElementById("menu_EditPopup").state;
  3100.   let contextMenuPopupState = document.getElementById("contentAreaContextMenu").state;
  3101.   let placesContextMenuPopupState = document.getElementById("placesContext").state;
  3102.  
  3103.   // The UI is visible if the Edit menu is opening or open, if the context menu
  3104.   // is open, or if the toolbar has been customized to include the Cut, Copy,
  3105.   // or Paste toolbar buttons.
  3106.   gEditUIVisible = editMenuPopupState == "showing" ||
  3107.                    editMenuPopupState == "open" ||
  3108.                    contextMenuPopupState == "showing" ||
  3109.                    contextMenuPopupState == "open" ||
  3110.                    placesContextMenuPopupState == "showing" ||
  3111.                    placesContextMenuPopupState == "open" ||
  3112.                    document.getElementById("cut-button") ||
  3113.                    document.getElementById("copy-button") ||
  3114.                    document.getElementById("paste-button") ? true : false;
  3115.  
  3116.   // If UI is visible, update the edit commands' enabled state to reflect
  3117.   // whether or not they are actually enabled for the current focus/selection.
  3118.   if (gEditUIVisible)
  3119.     goUpdateGlobalEditMenuItems();
  3120.  
  3121.   // Otherwise, enable all commands, so that keyboard shortcuts still work,
  3122.   // then lazily determine their actual enabled state when the user presses
  3123.   // a keyboard shortcut.
  3124.   else {
  3125.     goSetCommandEnabled("cmd_undo", true);
  3126.     goSetCommandEnabled("cmd_redo", true);
  3127.     goSetCommandEnabled("cmd_cut", true);
  3128.     goSetCommandEnabled("cmd_copy", true);
  3129.     goSetCommandEnabled("cmd_paste", true);
  3130.     goSetCommandEnabled("cmd_selectAll", true);
  3131.     goSetCommandEnabled("cmd_delete", true);
  3132.     goSetCommandEnabled("cmd_switchTextDirection", true);
  3133.   }
  3134. //@line 3503 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3135. }
  3136.  
  3137. var FullScreen =
  3138. {
  3139.   _XULNS: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
  3140.   toggle: function()
  3141.   {
  3142.     // show/hide all menubars, toolbars, and statusbars (except the full screen toolbar)
  3143.     this.showXULChrome("toolbar", window.fullScreen);
  3144.     this.showXULChrome("statusbar", window.fullScreen);
  3145.     document.getElementById("fullScreenItem").setAttribute("checked", !window.fullScreen);
  3146.  
  3147.     var fullScrToggler = document.getElementById("fullscr-toggler");
  3148.     if (!window.fullScreen) {
  3149.       // Add a tiny toolbar to receive mouseover and dragenter events, and provide affordance.
  3150.       // This will help simulate the "collapse" metaphor while also requiring less code and
  3151.       // events than raw listening of mouse coords.
  3152.       if (!fullScrToggler) {
  3153.         fullScrToggler = document.createElement("toolbar");
  3154.         fullScrToggler.id = "fullscr-toggler";
  3155.         fullScrToggler.setAttribute("customizable", "false");
  3156.         fullScrToggler.setAttribute("moz-collapsed", "true");
  3157.         var navBar = document.getElementById("nav-bar");
  3158.         navBar.parentNode.insertBefore(fullScrToggler, navBar);
  3159.       }
  3160.       fullScrToggler.addEventListener("mouseover", this._expandCallback, false);
  3161.       fullScrToggler.addEventListener("dragenter", this._expandCallback, false);
  3162.  
  3163.       if (gPrefService.getBoolPref("browser.fullscreen.autohide"))
  3164.         gBrowser.mPanelContainer.addEventListener("mousemove",
  3165.                                                   this._collapseCallback, false);
  3166.  
  3167.       document.addEventListener("keypress", this._keyToggleCallback, false);
  3168.       document.addEventListener("popupshown", this._setPopupOpen, false);
  3169.       document.addEventListener("popuphidden", this._setPopupOpen, false);
  3170.       this._shouldAnimate = true;
  3171.       this.mouseoverToggle(false);
  3172.  
  3173.       // Autohide prefs
  3174.       gPrefService.addObserver("browser.fullscreen", this, false);
  3175.     }
  3176.     else {
  3177.       document.removeEventListener("keypress", this._keyToggleCallback, false);
  3178.       document.removeEventListener("popupshown", this._setPopupOpen, false);
  3179.       document.removeEventListener("popuphidden", this._setPopupOpen, false);
  3180.       gPrefService.removeObserver("browser.fullscreen", this);
  3181.  
  3182.       if (fullScrToggler) {
  3183.         fullScrToggler.removeEventListener("mouseover", this._expandCallback, false);
  3184.         fullScrToggler.removeEventListener("dragenter", this._expandCallback, false);
  3185.       }
  3186.  
  3187.       // The user may quit fullscreen during an animation
  3188.       clearInterval(this._animationInterval);
  3189.       clearTimeout(this._animationTimeout);
  3190.       gNavToolbox.style.marginTop = "0px";
  3191.       if (this._isChromeCollapsed)
  3192.         this.mouseoverToggle(true);
  3193.       this._isAnimating = false;
  3194.       // This is needed if they use the context menu to quit fullscreen
  3195.       this._isPopupOpen = false;
  3196.  
  3197.       gBrowser.mPanelContainer.removeEventListener("mousemove",
  3198.                                                    this._collapseCallback, false);
  3199.     }
  3200.   },
  3201.  
  3202.   observe: function(aSubject, aTopic, aData)
  3203.   {
  3204.     if (aData == "browser.fullscreen.autohide") {
  3205.       if (gPrefService.getBoolPref("browser.fullscreen.autohide")) {
  3206.         gBrowser.mPanelContainer.addEventListener("mousemove",
  3207.                                                   this._collapseCallback, false);
  3208.       }
  3209.       else {
  3210.         gBrowser.mPanelContainer.removeEventListener("mousemove",
  3211.                                                      this._collapseCallback, false);
  3212.       }
  3213.     }
  3214.   },
  3215.  
  3216.   // Event callbacks
  3217.   _expandCallback: function()
  3218.   {
  3219.     FullScreen.mouseoverToggle(true);
  3220.   },
  3221.   _collapseCallback: function()
  3222.   {
  3223.     FullScreen.mouseoverToggle(false);
  3224.   },
  3225.   _keyToggleCallback: function(aEvent)
  3226.   {
  3227.     // if we can use the keyboard (eg Ctrl+L or Ctrl+E) to open the toolbars, we
  3228.     // should provide a way to collapse them too.
  3229.     if (aEvent.keyCode == aEvent.DOM_VK_ESCAPE) {
  3230.       FullScreen._shouldAnimate = false;
  3231.       FullScreen.mouseoverToggle(false, true);
  3232.     }
  3233.     // F6 is another shortcut to the address bar, but its not covered in OpenLocation()
  3234.     else if (aEvent.keyCode == aEvent.DOM_VK_F6)
  3235.       FullScreen.mouseoverToggle(true);
  3236.   },
  3237.  
  3238.   // Checks whether we are allowed to collapse the chrome
  3239.   _isPopupOpen: false,
  3240.   _isChromeCollapsed: false,
  3241.   _safeToCollapse: function(forceHide)
  3242.   {
  3243.     if (!gPrefService.getBoolPref("browser.fullscreen.autohide"))
  3244.       return false;
  3245.  
  3246.     // a popup menu is open in chrome: don't collapse chrome
  3247.     if (!forceHide && this._isPopupOpen)
  3248.       return false;
  3249.  
  3250.     // a textbox in chrome is focused (location bar anyone?): don't collapse chrome
  3251.     if (document.commandDispatcher.focusedElement &&
  3252.         document.commandDispatcher.focusedElement.ownerDocument == document &&
  3253.         document.commandDispatcher.focusedElement.localName == "input") {
  3254.       if (forceHide)
  3255.         // hidden textboxes that still have focus are bad bad bad
  3256.         document.commandDispatcher.focusedElement.blur();
  3257.       else
  3258.         return false;
  3259.     }
  3260.     return true;
  3261.   },
  3262.  
  3263.   _setPopupOpen: function(aEvent)
  3264.   {
  3265.     // Popups should only veto chrome collapsing if they were opened when the chrome was not collapsed.
  3266.     // Otherwise, they would not affect chrome and the user would expect the chrome to go away.
  3267.     // e.g. we wouldn't want the autoscroll icon firing this event, so when the user
  3268.     // toggles chrome when moving mouse to the top, it doesn't go away again.
  3269.     if (aEvent.type == "popupshown" && !FullScreen._isChromeCollapsed &&
  3270.         aEvent.target.localName != "tooltip" && aEvent.target.localName != "window")
  3271.       FullScreen._isPopupOpen = true;
  3272.     else if (aEvent.type == "popuphidden" && aEvent.target.localName != "tooltip" &&
  3273.              aEvent.target.localName != "window")
  3274.       FullScreen._isPopupOpen = false;
  3275.   },
  3276.  
  3277.   // Autohide helpers for the context menu item
  3278.   getAutohide: function(aItem)
  3279.   {
  3280.     aItem.setAttribute("checked", gPrefService.getBoolPref("browser.fullscreen.autohide"));
  3281.   },
  3282.   setAutohide: function()
  3283.   {
  3284.     gPrefService.setBoolPref("browser.fullscreen.autohide", !gPrefService.getBoolPref("browser.fullscreen.autohide"));
  3285.   },
  3286.  
  3287.   // Animate the toolbars disappearing
  3288.   _shouldAnimate: true,
  3289.   _isAnimating: false,
  3290.   _animationTimeout: null,
  3291.   _animationInterval: null,
  3292.   _animateUp: function()
  3293.   {
  3294.     // check again, the user may have done something before the animation was due to start
  3295.     if (!window.fullScreen || !FullScreen._safeToCollapse(false)) {
  3296.       FullScreen._isAnimating = false;
  3297.       FullScreen._shouldAnimate = true;
  3298.       return;
  3299.     }
  3300.  
  3301.     var animateFrameAmount = 2;
  3302.     function animateUpFrame() {
  3303.       animateFrameAmount *= 2;
  3304.       if (animateFrameAmount >=
  3305.           (gNavToolbox.boxObject.height + gBrowser.mStrip.boxObject.height)) {
  3306.         // We've animated enough
  3307.         clearInterval(FullScreen._animationInterval);
  3308.         gNavToolbox.style.marginTop = "0px";
  3309.         FullScreen._isAnimating = false;
  3310.         FullScreen._shouldAnimate = false; // Just to make sure
  3311.         FullScreen.mouseoverToggle(false);
  3312.         return;
  3313.       }
  3314.       gNavToolbox.style.marginTop = (animateFrameAmount * -1) + "px";
  3315.     }
  3316.  
  3317.     FullScreen._animationInterval = setInterval(animateUpFrame, 70);
  3318.   },
  3319.  
  3320.   mouseoverToggle: function(aShow, forceHide)
  3321.   {
  3322.     // Don't do anything if:
  3323.     // a) we're already in the state we want,
  3324.     // b) we're animating and will become collapsed soon, or
  3325.     // c) we can't collapse because it would be undesirable right now
  3326.     if (aShow != this._isChromeCollapsed || (!aShow && this._isAnimating) ||
  3327.         (!aShow && !this._safeToCollapse(forceHide)))
  3328.       return;
  3329.  
  3330.     // browser.fullscreen.animateUp
  3331.     // 0 - never animate up
  3332.     // 1 - animate only for first collapse after entering fullscreen (default for perf's sake)
  3333.     // 2 - animate every time it collapses
  3334.     if (gPrefService.getIntPref("browser.fullscreen.animateUp") == 0)
  3335.       this._shouldAnimate = false;
  3336.  
  3337.     if (!aShow && this._shouldAnimate) {
  3338.       this._isAnimating = true;
  3339.       this._shouldAnimate = false;
  3340.       this._animationTimeout = setTimeout(this._animateUp, 800);
  3341.       return;
  3342.     }
  3343.  
  3344.     // The chrome is collapsed so don't spam needless mousemove events
  3345.     if (aShow) {
  3346.       gBrowser.mPanelContainer.addEventListener("mousemove",
  3347.                                                 this._collapseCallback, false);
  3348.     }
  3349.     else {
  3350.       gBrowser.mPanelContainer.removeEventListener("mousemove",
  3351.                                                    this._collapseCallback, false);
  3352.     }
  3353.  
  3354.     gBrowser.mStrip.setAttribute("moz-collapsed", !aShow);
  3355.     var allFSToolbars = document.getElementsByTagNameNS(this._XULNS, "toolbar");
  3356.     for (var i = 0; i < allFSToolbars.length; i++) {
  3357.       if (allFSToolbars[i].getAttribute("fullscreentoolbar") == "true")
  3358.         allFSToolbars[i].setAttribute("moz-collapsed", !aShow);
  3359.     }
  3360.     document.getElementById("fullscr-toggler").setAttribute("moz-collapsed", aShow);
  3361.     this._isChromeCollapsed = !aShow;
  3362.     if (gPrefService.getIntPref("browser.fullscreen.animateUp") == 2)
  3363.       this._shouldAnimate = true;
  3364.   },
  3365.  
  3366.   showXULChrome: function(aTag, aShow)
  3367.   {
  3368.     var els = document.getElementsByTagNameNS(this._XULNS, aTag);
  3369.  
  3370.     for (var i = 0; i < els.length; ++i) {
  3371.       // XXX don't interfere with previously collapsed toolbars
  3372.       if (els[i].getAttribute("fullscreentoolbar") == "true") {
  3373.         if (!aShow) {
  3374.  
  3375.           var toolbarMode = els[i].getAttribute("mode");
  3376.           if (toolbarMode != "text") {
  3377.             els[i].setAttribute("saved-mode", toolbarMode);
  3378.             els[i].setAttribute("saved-iconsize",
  3379.                                 els[i].getAttribute("iconsize"));
  3380.             els[i].setAttribute("mode", "icons");
  3381.             els[i].setAttribute("iconsize", "small");
  3382.           }
  3383.  
  3384.           // Give the main nav bar the fullscreen context menu, otherwise remove it
  3385.           // to prevent breakage
  3386.           els[i].setAttribute("saved-context",
  3387.                               els[i].getAttribute("context"));
  3388.           if (els[i].id == "nav-bar")
  3389.             els[i].setAttribute("context", "autohide-context");
  3390.           else
  3391.             els[i].removeAttribute("context");
  3392.  
  3393.           // Set the inFullscreen attribute to allow specific styling
  3394.           // in fullscreen mode
  3395.           els[i].setAttribute("inFullscreen", true);
  3396.         }
  3397.         else {
  3398.           function restoreAttr(attrName) {
  3399.             var savedAttr = "saved-" + attrName;
  3400.             if (els[i].hasAttribute(savedAttr)) {
  3401.               els[i].setAttribute(attrName, els[i].getAttribute(savedAttr));
  3402.               els[i].removeAttribute(savedAttr);
  3403.             }
  3404.           }
  3405.  
  3406.           restoreAttr("mode");
  3407.           restoreAttr("iconsize");
  3408.           restoreAttr("context");
  3409.  
  3410.           els[i].removeAttribute("inFullscreen");
  3411.         }
  3412.       } else {
  3413.         // use moz-collapsed so it doesn't persist hidden/collapsed,
  3414.         // so that new windows don't have missing toolbars
  3415.         if (aShow)
  3416.           els[i].removeAttribute("moz-collapsed");
  3417.         else
  3418.           els[i].setAttribute("moz-collapsed", "true");
  3419.       }
  3420.     }
  3421.  
  3422.     if (aShow)
  3423.       gNavToolbox.removeAttribute("inFullscreen");
  3424.     else
  3425.       gNavToolbox.setAttribute("inFullscreen", true);
  3426.  
  3427. //@line 3796 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3428.     var controls = document.getElementsByAttribute("fullscreencontrol", "true");
  3429.     for (var i = 0; i < controls.length; ++i)
  3430.       controls[i].hidden = aShow;
  3431. //@line 3800 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3432.   }
  3433. };
  3434.  
  3435. /**
  3436.  * Returns true if |aMimeType| is text-based, false otherwise.
  3437.  *
  3438.  * @param aMimeType
  3439.  *        The MIME type to check.
  3440.  *
  3441.  * If adding types to this function, please also check the similar 
  3442.  * function in findbar.xml
  3443.  */
  3444. function mimeTypeIsTextBased(aMimeType)
  3445. {
  3446.   return /^text\/|\+xml$/.test(aMimeType) ||
  3447.          aMimeType == "application/x-javascript" ||
  3448.          aMimeType == "application/javascript" ||
  3449.          aMimeType == "application/xml" ||
  3450.          aMimeType == "mozilla.application/cached-xul";
  3451. }
  3452.  
  3453. var XULBrowserWindow = {
  3454.   // Stored Status, Link and Loading values
  3455.   status: "",
  3456.   defaultStatus: "",
  3457.   jsStatus: "",
  3458.   jsDefaultStatus: "",
  3459.   overLink: "",
  3460.   startTime: 0,
  3461.   statusText: "",
  3462.   lastURI: null,
  3463.   isBusy: false,
  3464.  
  3465.   statusTimeoutInEffect: false,
  3466.  
  3467.   QueryInterface: function (aIID) {
  3468.     if (aIID.equals(Ci.nsIWebProgressListener) ||
  3469.         aIID.equals(Ci.nsIWebProgressListener2) ||
  3470.         aIID.equals(Ci.nsISupportsWeakReference) ||
  3471.         aIID.equals(Ci.nsIXULBrowserWindow) ||
  3472.         aIID.equals(Ci.nsISupports))
  3473.       return this;
  3474.     throw Cr.NS_NOINTERFACE;
  3475.   },
  3476.  
  3477.   get statusMeter () {
  3478.     delete this.statusMeter;
  3479.     return this.statusMeter = document.getElementById("statusbar-icon");
  3480.   },
  3481.   get stopCommand () {
  3482.     delete this.stopCommand;
  3483.     return this.stopCommand = document.getElementById("Browser:Stop");
  3484.   },
  3485.   get reloadCommand () {
  3486.     delete this.reloadCommand;
  3487.     return this.reloadCommand = document.getElementById("Browser:Reload");
  3488.   },
  3489.   get statusTextField () {
  3490.     delete this.statusTextField;
  3491.     return this.statusTextField = document.getElementById("statusbar-display");
  3492.   },
  3493.   get securityButton () {
  3494.     delete this.securityButton;
  3495.     return this.securityButton = document.getElementById("security-button");
  3496.   },
  3497.   get isImage () {
  3498.     delete this.isImage;
  3499.     return this.isImage = document.getElementById("isImage");
  3500.   },
  3501.   get _uriFixup () {
  3502.     delete this._uriFixup;
  3503.     return this._uriFixup = Cc["@mozilla.org/docshell/urifixup;1"]
  3504.                               .getService(Ci.nsIURIFixup);
  3505.   },
  3506.  
  3507.   init: function () {
  3508.     this.throbberElement = document.getElementById("navigator-throbber");
  3509.  
  3510.     // Initialize the security button's state and tooltip text.  Remember to reset
  3511.     // _hostChanged, otherwise onSecurityChange will short circuit.
  3512.     var securityUI = gBrowser.securityUI;
  3513.     this._hostChanged = true;
  3514.     this.onSecurityChange(null, null, securityUI.state);
  3515.   },
  3516.  
  3517.   destroy: function () {
  3518.     // XXXjag to avoid leaks :-/, see bug 60729
  3519.     delete this.throbberElement;
  3520.     delete this.statusMeter;
  3521.     delete this.stopCommand;
  3522.     delete this.reloadCommand;
  3523.     delete this.statusTextField;
  3524.     delete this.securityButton;
  3525.     delete this.statusText;
  3526.     delete this.lastURI;
  3527.   },
  3528.  
  3529.   setJSStatus: function (status) {
  3530.     this.jsStatus = status;
  3531.     this.updateStatusField();
  3532.   },
  3533.  
  3534.   setJSDefaultStatus: function (status) {
  3535.     this.jsDefaultStatus = status;
  3536.     this.updateStatusField();
  3537.   },
  3538.  
  3539.   setDefaultStatus: function (status) {
  3540.     this.defaultStatus = status;
  3541.     this.updateStatusField();
  3542.   },
  3543.  
  3544.   setOverLink: function (link, b) {
  3545.     // Encode bidirectional formatting characters.
  3546.     // (RFC 3987 sections 3.2 and 4.1 paragraph 6)
  3547.     this.overLink = link.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g,
  3548.                                  encodeURIComponent);
  3549.     this.updateStatusField();
  3550.   },
  3551.  
  3552.   updateStatusField: function () {
  3553.     var text = this.overLink || this.status || this.jsStatus || this.jsDefaultStatus || this.defaultStatus;
  3554.  
  3555.     // check the current value so we don't trigger an attribute change
  3556.     // and cause needless (slow!) UI updates
  3557.     if (this.statusText != text) {
  3558.       this.statusTextField.label = text;
  3559.       this.statusText = text;
  3560.     }
  3561.   },
  3562.   
  3563.   onLinkIconAvailable: function (aBrowser) {
  3564.     if (gProxyFavIcon && gBrowser.userTypedValue === null)
  3565.       PageProxySetIcon(aBrowser.mIconURL); // update the favicon in the URL bar
  3566.   },
  3567.  
  3568.   onProgressChange: function (aWebProgress, aRequest,
  3569.                               aCurSelfProgress, aMaxSelfProgress,
  3570.                               aCurTotalProgress, aMaxTotalProgress) {
  3571.     if (aMaxTotalProgress > 0) {
  3572.       // This is highly optimized.  Don't touch this code unless
  3573.       // you are intimately familiar with the cost of setting
  3574.       // attrs on XUL elements. -- hyatt
  3575.       var percentage = (aCurTotalProgress * 100) / aMaxTotalProgress;
  3576.       this.statusMeter.value = percentage;
  3577.     }
  3578.   },
  3579.  
  3580.   onProgressChange64: function (aWebProgress, aRequest,
  3581.                                 aCurSelfProgress, aMaxSelfProgress,
  3582.                                 aCurTotalProgress, aMaxTotalProgress) {
  3583.     return this.onProgressChange(aWebProgress, aRequest,
  3584.       aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress,
  3585.       aMaxTotalProgress);
  3586.   },
  3587.  
  3588.   onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) {
  3589.     const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
  3590.     const nsIChannel = Components.interfaces.nsIChannel;
  3591.     if (aStateFlags & nsIWebProgressListener.STATE_START) {
  3592.       // This (thanks to the filter) is a network start or the first
  3593.       // stray request (the first request outside of the document load),
  3594.       // initialize the throbber and his friends.
  3595.  
  3596.       // Call start document load listeners (only if this is a network load)
  3597.       if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK &&
  3598.           aRequest && aWebProgress.DOMWindow == content)
  3599.         this.startDocumentLoad(aRequest);
  3600.  
  3601.       this.isBusy = true;
  3602.  
  3603.       if (this.throbberElement) {
  3604.         // Turn the throbber on.
  3605.         this.throbberElement.setAttribute("busy", "true");
  3606.       }
  3607.  
  3608.       // Turn the status meter on.
  3609.       this.statusMeter.value = 0;  // be sure to clear the progress bar
  3610.       if (gProgressCollapseTimer) {
  3611.         window.clearTimeout(gProgressCollapseTimer);
  3612.         gProgressCollapseTimer = null;
  3613.       }
  3614.       else
  3615.         this.statusMeter.parentNode.collapsed = false;
  3616.  
  3617.       // XXX: This needs to be based on window activity...
  3618.       this.stopCommand.removeAttribute("disabled");
  3619.     }
  3620.     else if (aStateFlags & nsIWebProgressListener.STATE_STOP) {
  3621.       if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK) {
  3622.         if (aWebProgress.DOMWindow == content) {
  3623.           if (aRequest)
  3624.             this.endDocumentLoad(aRequest, aStatus);
  3625.           if (!gBrowser.mTabbedMode && !gBrowser.mCurrentBrowser.mIconURL)
  3626.             gBrowser.useDefaultIcon(gBrowser.mCurrentTab);
  3627.         }
  3628.       }
  3629.  
  3630.       // This (thanks to the filter) is a network stop or the last
  3631.       // request stop outside of loading the document, stop throbbers
  3632.       // and progress bars and such
  3633.       if (aRequest) {
  3634.         let msg = "";
  3635.         let location;
  3636.         // Get the URI either from a channel or a pseudo-object
  3637.         if (aRequest instanceof nsIChannel || "URI" in aRequest) {
  3638.           location = aRequest.URI;
  3639.  
  3640.           // For keyword URIs clear the user typed value since they will be changed into real URIs
  3641.           if (location.scheme == "keyword" && aWebProgress.DOMWindow == content)
  3642.             gBrowser.userTypedValue = null;
  3643.  
  3644.           if (location.spec != "about:blank") {
  3645.             switch (aStatus) {
  3646.               case Components.results.NS_BINDING_ABORTED:
  3647.                 msg = gNavigatorBundle.getString("nv_stopped");
  3648.                 break;
  3649.               case Components.results.NS_ERROR_NET_TIMEOUT:
  3650.                 msg = gNavigatorBundle.getString("nv_timeout");
  3651.                 break;
  3652.             }
  3653.           }
  3654.         }
  3655.         // If msg is false then we did not have an error (channel may have
  3656.         // been null, in the case of a stray image load).
  3657.         if (!msg && (!location || location.spec != "about:blank"))
  3658.           msg = gNavigatorBundle.getString("nv_done");
  3659.  
  3660.         this.status = "";
  3661.         this.setDefaultStatus(msg);
  3662.  
  3663.         // Disable menu entries for images, enable otherwise
  3664.         if (content.document && mimeTypeIsTextBased(content.document.contentType))
  3665.           this.isImage.removeAttribute('disabled');
  3666.         else
  3667.           this.isImage.setAttribute('disabled', 'true');
  3668.       }
  3669.  
  3670.       this.isBusy = false;
  3671.  
  3672.       // Turn the progress meter and throbber off.
  3673.       gProgressCollapseTimer = window.setTimeout(function () {
  3674.         gProgressMeterPanel.collapsed = true;
  3675.         gProgressCollapseTimer = null;
  3676.       }, 100);
  3677.  
  3678.       if (this.throbberElement)
  3679.         this.throbberElement.removeAttribute("busy");
  3680.  
  3681.       this.stopCommand.setAttribute("disabled", "true");
  3682.     }
  3683.   },
  3684.  
  3685.   onLocationChange: function (aWebProgress, aRequest, aLocationURI) {
  3686.     var location = aLocationURI ? aLocationURI.spec : "";
  3687.     this._hostChanged = true;
  3688.  
  3689.     if (document.tooltipNode) {
  3690.       // Optimise for the common case
  3691.       if (aWebProgress.DOMWindow == content) {
  3692.         document.getElementById("aHTMLTooltip").hidePopup();
  3693.         document.tooltipNode = null;
  3694.       }
  3695.       else {
  3696.         for (let tooltipWindow =
  3697.                document.tooltipNode.ownerDocument.defaultView;
  3698.              tooltipWindow != tooltipWindow.parent;
  3699.              tooltipWindow = tooltipWindow.parent) {
  3700.           if (tooltipWindow == aWebProgress.DOMWindow) {
  3701.             document.getElementById("aHTMLTooltip").hidePopup();
  3702.             document.tooltipNode = null;
  3703.             break;
  3704.           }
  3705.         }
  3706.       }
  3707.     }
  3708.  
  3709.     // This code here does not compare uris exactly when determining
  3710.     // whether or not the message should be hidden since the message
  3711.     // may be prematurely hidden when an install is invoked by a click
  3712.     // on a link that looks like this:
  3713.     //
  3714.     // <a href="#" onclick="return install();">Install Foo</a>
  3715.     //
  3716.     // - which fires a onLocationChange message to uri + '#'...
  3717.     var selectedBrowser = gBrowser.selectedBrowser;
  3718.     if (selectedBrowser.lastURI) {
  3719.       let oldSpec = selectedBrowser.lastURI.spec;
  3720.       let oldIndexOfHash = oldSpec.indexOf("#");
  3721.       if (oldIndexOfHash != -1)
  3722.         oldSpec = oldSpec.substr(0, oldIndexOfHash);
  3723.       let newSpec = location;
  3724.       let newIndexOfHash = newSpec.indexOf("#");
  3725.       if (newIndexOfHash != -1)
  3726.         newSpec = newSpec.substr(0, newSpec.indexOf("#"));
  3727.       if (newSpec != oldSpec) {
  3728.         // Remove all the notifications, except for those which want to
  3729.         // persist across the first location change.
  3730.         let nBox = gBrowser.getNotificationBox(selectedBrowser);
  3731.         nBox.removeTransientNotifications();
  3732.       }
  3733.     }
  3734.     selectedBrowser.lastURI = aLocationURI;
  3735.  
  3736.     // Disable menu entries for images, enable otherwise
  3737.     if (content.document && mimeTypeIsTextBased(content.document.contentType))
  3738.       this.isImage.removeAttribute('disabled');
  3739.     else
  3740.       this.isImage.setAttribute('disabled', 'true');
  3741.  
  3742.     this.setOverLink("", null);
  3743.  
  3744.     // We should probably not do this if the value has changed since the user
  3745.     // searched
  3746.     // Update urlbar only if a new page was loaded on the primary content area
  3747.     // Do not update urlbar if there was a subframe navigation
  3748.  
  3749.     var browser = gBrowser.selectedBrowser;
  3750.     if (aWebProgress.DOMWindow == content) {
  3751.       if ((location == "about:blank" && !content.opener) ||
  3752.           location == "") {  // Second condition is for new tabs, otherwise
  3753.                              // reload function is enabled until tab is refreshed.
  3754.         this.reloadCommand.setAttribute("disabled", "true");
  3755.       } else {
  3756.         this.reloadCommand.removeAttribute("disabled");
  3757.       }
  3758.  
  3759.       if (!gBrowser.mTabbedMode && aWebProgress.isLoadingDocument)
  3760.         gBrowser.setIcon(gBrowser.mCurrentTab, null);
  3761.  
  3762.       if (gURLBar) {
  3763.         // Strip off "wyciwyg://" and passwords for the location bar
  3764.         let uri = aLocationURI;
  3765.         try {
  3766.           uri = this._uriFixup.createExposableURI(uri);
  3767.         } catch (e) {}
  3768.         URLBarSetURI(uri, true);
  3769.  
  3770.         // Update starring UI
  3771.         PlacesStarButton.updateState();
  3772.       }
  3773.     }
  3774.     UpdateBackForwardCommands(gBrowser.webNavigation);
  3775.  
  3776.     if (gFindBar.findMode != gFindBar.FIND_NORMAL) {
  3777.       // Close the Find toolbar if we're in old-style TAF mode
  3778.       gFindBar.close();
  3779.     }
  3780.  
  3781.     // XXXmano new-findbar, do something useful once it lands.
  3782.     // Of course, this is especially wrong with bfcache on...
  3783.  
  3784.     // fix bug 253793 - turn off highlight when page changes
  3785.     gFindBar.getElement("highlight").checked = false;
  3786.  
  3787.     // See bug 358202, when tabs are switched during a drag operation,
  3788.     // timers don't fire on windows (bug 203573)
  3789.     if (aRequest)
  3790.       setTimeout(function () { XULBrowserWindow.asyncUpdateUI(); }, 0);
  3791.     else
  3792.       this.asyncUpdateUI();
  3793.   },
  3794.   
  3795.   asyncUpdateUI: function () {
  3796.     FeedHandler.updateFeeds();
  3797.     BrowserSearch.updateSearchButton();
  3798.   },
  3799.  
  3800.   onStatusChange: function (aWebProgress, aRequest, aStatus, aMessage) {
  3801.     this.status = aMessage;
  3802.     this.updateStatusField();
  3803.   },
  3804.  
  3805.   // Properties used to cache security state used to update the UI
  3806.   _state: null,
  3807.   _host: undefined,
  3808.   _tooltipText: null,
  3809.   _hostChanged: false, // onLocationChange will flip this bit
  3810.  
  3811.   onSecurityChange: function (aWebProgress, aRequest, aState) {
  3812.     // Don't need to do anything if the data we use to update the UI hasn't
  3813.     // changed
  3814.     if (this._state == aState &&
  3815.         this._tooltipText == gBrowser.securityUI.tooltipText &&
  3816.         !this._hostChanged) {
  3817. //@line 4196 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  3818.       return;
  3819.     }
  3820.     this._state = aState;
  3821.  
  3822.     try {
  3823.       this._host = gBrowser.contentWindow.location.host;
  3824.     } catch(ex) {
  3825.       this._host = null;
  3826.     }
  3827.  
  3828.     this._hostChanged = false;
  3829.     this._tooltipText = gBrowser.securityUI.tooltipText
  3830.  
  3831.     // aState is defined as a bitmask that may be extended in the future.
  3832.     // We filter out any unknown bits before testing for known values.
  3833.     const wpl = Components.interfaces.nsIWebProgressListener;
  3834.     const wpl_security_bits = wpl.STATE_IS_SECURE |
  3835.                               wpl.STATE_IS_BROKEN |
  3836.                               wpl.STATE_IS_INSECURE |
  3837.                               wpl.STATE_SECURE_HIGH |
  3838.                               wpl.STATE_SECURE_MED |
  3839.                               wpl.STATE_SECURE_LOW;
  3840.     var level;
  3841.     var setHost = false;
  3842.  
  3843.     switch (this._state & wpl_security_bits) {
  3844.       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH:
  3845.         level = "high";
  3846.         setHost = true;
  3847.         break;
  3848.       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_MED:
  3849.       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW:
  3850.         level = "low";
  3851.         setHost = true;
  3852.         break;
  3853.       case wpl.STATE_IS_BROKEN:
  3854.         level = "broken";
  3855.         break;
  3856.     }
  3857.  
  3858.     if (level) {
  3859.       this.securityButton.setAttribute("level", level);
  3860.       this.securityButton.hidden = false;
  3861.       // We don't style the Location Bar based on the the 'level' attribute
  3862.       // anymore, but still set it for third-party themes.
  3863.       if (gURLBar)
  3864.         gURLBar.setAttribute("level", level);
  3865.     } else {
  3866.       this.securityButton.hidden = true;
  3867.       this.securityButton.removeAttribute("level");
  3868.       if (gURLBar)
  3869.         gURLBar.removeAttribute("level");
  3870.     }
  3871.  
  3872.     if (setHost && this._host)
  3873.       this.securityButton.setAttribute("label", this._host);
  3874.     else
  3875.       this.securityButton.removeAttribute("label");
  3876.  
  3877.     this.securityButton.setAttribute("tooltiptext", this._tooltipText);
  3878.  
  3879.     // Don't pass in the actual location object, since it can cause us to 
  3880.     // hold on to the window object too long.  Just pass in the fields we
  3881.     // care about. (bug 424829)
  3882.     var location = gBrowser.contentWindow.location;
  3883.     var locationObj = {};
  3884.     try {
  3885.       locationObj.host = location.host;
  3886.       locationObj.hostname = location.hostname;
  3887.       locationObj.port = location.port;
  3888.     } catch (ex) {
  3889.       // Can sometimes throw if the URL being visited has no host/hostname,
  3890.       // e.g. about:blank. The _state for these pages means we won't need these
  3891.       // properties anyways, though.
  3892.     }
  3893.     gIdentityHandler.checkIdentity(this._state, locationObj);
  3894.   },
  3895.  
  3896.   // simulate all change notifications after switching tabs
  3897.   onUpdateCurrentBrowser: function (aStateFlags, aStatus, aMessage, aTotalProgress) {
  3898.     if (FullZoom.updateBackgroundTabs)
  3899.       FullZoom.onLocationChange(gBrowser.currentURI);
  3900.     var nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
  3901.     var loadingDone = aStateFlags & nsIWebProgressListener.STATE_STOP;
  3902.     // use a pseudo-object instead of a (potentially non-existing) channel for getting
  3903.     // a correct error message - and make sure that the UI is always either in
  3904.     // loading (STATE_START) or done (STATE_STOP) mode
  3905.     this.onStateChange(
  3906.       gBrowser.webProgress,
  3907.       { URI: gBrowser.currentURI },
  3908.       loadingDone ? nsIWebProgressListener.STATE_STOP : nsIWebProgressListener.STATE_START,
  3909.       aStatus
  3910.     );
  3911.     // status message and progress value are undefined if we're done with loading
  3912.     if (loadingDone)
  3913.       return;
  3914.     this.onStatusChange(gBrowser.webProgress, null, 0, aMessage);
  3915.     this.onProgressChange(gBrowser.webProgress, 0, 0, aTotalProgress, 1);
  3916.   },
  3917.  
  3918.   startDocumentLoad: function (aRequest) {
  3919.     // clear out feed data
  3920.     gBrowser.mCurrentBrowser.feeds = null;
  3921.  
  3922.     // clear out search-engine data
  3923.     gBrowser.mCurrentBrowser.engines = null;    
  3924.  
  3925.     var uri = aRequest.QueryInterface(Ci.nsIChannel).URI;
  3926.     var observerService = Cc["@mozilla.org/observer-service;1"]
  3927.                             .getService(Ci.nsIObserverService);
  3928.  
  3929.     if (gURLBar &&
  3930.         gURLBar.value == "" &&
  3931.         getWebNavigation().currentURI.spec == "about:blank")
  3932.       URLBarSetURI(uri);
  3933.  
  3934.     try {
  3935.       observerService.notifyObservers(content, "StartDocumentLoad", uri.spec);
  3936.     } catch (e) {
  3937.     }
  3938.   },
  3939.  
  3940.   endDocumentLoad: function (aRequest, aStatus) {
  3941.     var urlStr = aRequest.QueryInterface(Ci.nsIChannel).originalURI.spec;
  3942.  
  3943.     var observerService = Cc["@mozilla.org/observer-service;1"]
  3944.                             .getService(Ci.nsIObserverService);
  3945.  
  3946.     var notification = Components.isSuccessCode(aStatus) ? "EndDocumentLoad" : "FailDocumentLoad";
  3947.     try {
  3948.       observerService.notifyObservers(content, notification, urlStr);
  3949.     } catch (e) {
  3950.     }
  3951.   }
  3952. }
  3953.  
  3954. var TabsProgressListener = {
  3955.   onProgressChange: function (aBrowser, aWebProgress, aRequest,
  3956.                               aCurSelfProgress, aMaxSelfProgress,
  3957.                               aCurTotalProgress, aMaxTotalProgress) {
  3958.   },
  3959.  
  3960.   onStateChange: function (aBrowser, aWebProgress, aRequest, aStateFlags, aStatus) {
  3961.   },
  3962.  
  3963.   onLocationChange: function (aBrowser, aWebProgress, aRequest, aLocationURI) {
  3964.     // Filter out any sub-frame loads
  3965.     if (aBrowser.contentWindow == aWebProgress.DOMWindow)
  3966.       FullZoom.onLocationChange(aLocationURI, aBrowser);
  3967.   },
  3968.   
  3969.   onStatusChange: function (aBrowser, aWebProgress, aRequest, aStatus, aMessage) {
  3970.   },
  3971.  
  3972.   onRefreshAttempted: function (aBrowser, aWebProgress, aURI, aDelay, aSameURI) {
  3973.     if (gPrefService.getBoolPref("accessibility.blockautorefresh")) {
  3974.       let brandBundle = document.getElementById("bundle_brand");
  3975.       let brandShortName = brandBundle.getString("brandShortName");
  3976.       let refreshButtonText =
  3977.         gNavigatorBundle.getString("refreshBlocked.goButton");
  3978.       let refreshButtonAccesskey =
  3979.         gNavigatorBundle.getString("refreshBlocked.goButton.accesskey");
  3980.       let message =
  3981.         gNavigatorBundle.getFormattedString(aSameURI ? "refreshBlocked.refreshLabel"
  3982.                                                      : "refreshBlocked.redirectLabel",
  3983.                                             [brandShortName]);
  3984.       let docShell = aWebProgress.DOMWindow
  3985.                                  .QueryInterface(Ci.nsIInterfaceRequestor)
  3986.                                  .getInterface(Ci.nsIWebNavigation)
  3987.                                  .QueryInterface(Ci.nsIDocShell);
  3988.       let notificationBox = gBrowser.getNotificationBox(aBrowser);
  3989.       let notification = notificationBox.getNotificationWithValue("refresh-blocked");
  3990.       if (notification) {
  3991.         notification.label = message;
  3992.         notification.refreshURI = aURI;
  3993.         notification.delay = aDelay;
  3994.         notification.docShell = docShell;
  3995.       } else {
  3996.         let buttons = [{
  3997.           label: refreshButtonText,
  3998.           accessKey: refreshButtonAccesskey,
  3999.           callback: function (aNotification, aButton) {
  4000.             var refreshURI = aNotification.docShell
  4001.                                           .QueryInterface(Ci.nsIRefreshURI);
  4002.             refreshURI.forceRefreshURI(aNotification.refreshURI,
  4003.                                        aNotification.delay, true);
  4004.           }
  4005.         }];
  4006.         notification =
  4007.           notificationBox.appendNotification(message, "refresh-blocked",
  4008.                                              "chrome://browser/skin/Info.png",
  4009.                                              notificationBox.PRIORITY_INFO_MEDIUM,
  4010.                                              buttons);
  4011.         notification.refreshURI = aURI;
  4012.         notification.delay = aDelay;
  4013.         notification.docShell = docShell;
  4014.       }
  4015.       return false;
  4016.     }
  4017.     return true;
  4018.   },
  4019.  
  4020.   onSecurityChange: function (aBrowser, aWebProgress, aRequest, aState) {
  4021.   }
  4022. }
  4023.  
  4024. function nsBrowserAccess()
  4025. {
  4026. }
  4027.  
  4028. nsBrowserAccess.prototype =
  4029. {
  4030.   QueryInterface : function(aIID)
  4031.   {
  4032.     if (aIID.equals(Ci.nsIBrowserDOMWindow) ||
  4033.         aIID.equals(Ci.nsISupports))
  4034.       return this;
  4035.     throw Components.results.NS_NOINTERFACE;
  4036.   },
  4037.  
  4038.   openURI : function(aURI, aOpener, aWhere, aContext)
  4039.   {
  4040.     var newWindow = null;
  4041.     var referrer = null;
  4042.     var isExternal = (aContext == Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL);
  4043.  
  4044.     if (isExternal && aURI && aURI.schemeIs("chrome")) {
  4045.       dump("use -chrome command-line option to load external chrome urls\n");
  4046.       return null;
  4047.     }
  4048.  
  4049.     var loadflags = isExternal ?
  4050.                        Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL :
  4051.                        Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
  4052.     var location;
  4053.     if (aWhere == Ci.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW)
  4054.       aWhere = gPrefService.getIntPref("browser.link.open_newwindow");
  4055.     switch (aWhere) {
  4056.       case Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW :
  4057.         // FIXME: Bug 408379. So how come this doesn't send the
  4058.         // referrer like the other loads do?
  4059.         var url = aURI ? aURI.spec : "about:blank";
  4060.         // Pass all params to openDialog to ensure that "url" isn't passed through
  4061.         // loadOneOrMoreURIs, which splits based on "|"
  4062.         newWindow = openDialog(getBrowserURL(), "_blank", "all,dialog=no", url, null, null, null);
  4063.         break;
  4064.       case Ci.nsIBrowserDOMWindow.OPEN_NEWTAB :
  4065.         let win, needToFocusWin;
  4066.  
  4067.         // try the current window.  if we're in a popup, fall back on the most recent browser window
  4068.         if (!window.document.documentElement.getAttribute("chromehidden"))
  4069.           win = window;
  4070.         else {
  4071.           var browserGlue = Cc[GLUE_CID].getService(Ci.nsIBrowserGlue);
  4072.           win = browserGlue.getMostRecentBrowserWindow();
  4073.           needToFocusWin = true;
  4074.         }
  4075.  
  4076.         if (!win) {
  4077.           // we couldn't find a suitable window, a new one needs to be opened.
  4078.           return null;
  4079.         }
  4080.         var loadInBackground = gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground");
  4081.         var newTab = win.gBrowser.loadOneTab("about:blank", null, null, null, loadInBackground, false);
  4082.         newWindow = win.gBrowser.getBrowserForTab(newTab).docShell
  4083.                                 .QueryInterface(Ci.nsIInterfaceRequestor)
  4084.                                 .getInterface(Ci.nsIDOMWindow);
  4085.         try {
  4086.           if (aURI) {
  4087.             if (aOpener) {
  4088.               location = aOpener.location;
  4089.               referrer =
  4090.                       Components.classes["@mozilla.org/network/io-service;1"]
  4091.                                 .getService(Components.interfaces.nsIIOService)
  4092.                                 .newURI(location, null, null);
  4093.             }
  4094.             newWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  4095.                      .getInterface(Ci.nsIWebNavigation)
  4096.                      .loadURI(aURI.spec, loadflags, referrer, null, null);
  4097.           }
  4098.           if (needToFocusWin || (!loadInBackground && isExternal))
  4099.             newWindow.focus();
  4100.         } catch(e) {
  4101.         }
  4102.         break;
  4103.       default : // OPEN_CURRENTWINDOW or an illegal value
  4104.         try {
  4105.           if (aOpener) {
  4106.             newWindow = aOpener.top;
  4107.             if (aURI) {
  4108.               location = aOpener.location;
  4109.               referrer =
  4110.                       Components.classes["@mozilla.org/network/io-service;1"]
  4111.                                 .getService(Components.interfaces.nsIIOService)
  4112.                                 .newURI(location, null, null);
  4113.  
  4114.               newWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  4115.                        .getInterface(nsIWebNavigation)
  4116.                        .loadURI(aURI.spec, loadflags, referrer, null, null);
  4117.             }
  4118.           } else {
  4119.             newWindow = gBrowser.selectedBrowser.docShell
  4120.                                 .QueryInterface(Ci.nsIInterfaceRequestor)
  4121.                                 .getInterface(Ci.nsIDOMWindow);
  4122.             if (aURI) {
  4123.               gBrowser.loadURIWithFlags(aURI.spec, loadflags, null, 
  4124.                                         null, null);
  4125.             }
  4126.           }
  4127.           if(!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground"))
  4128.             content.focus();
  4129.         } catch(e) {
  4130.         }
  4131.     }
  4132.     return newWindow;
  4133.   },
  4134.  
  4135.   isTabContentWindow : function(aWindow)
  4136.   {
  4137.     return gBrowser.browsers.some(function (browser) browser.contentWindow == aWindow);
  4138.   }
  4139. }
  4140.  
  4141. function onViewToolbarsPopupShowing(aEvent)
  4142. {
  4143.   var popup = aEvent.target;
  4144.   var i;
  4145.  
  4146.   // Empty the menu
  4147.   for (i = popup.childNodes.length-1; i >= 0; --i) {
  4148.     var deadItem = popup.childNodes[i];
  4149.     if (deadItem.hasAttribute("toolbarindex"))
  4150.       popup.removeChild(deadItem);
  4151.   }
  4152.  
  4153.   var firstMenuItem = popup.firstChild;
  4154.  
  4155.   for (i = 0; i < gNavToolbox.childNodes.length; ++i) {
  4156.     var toolbar = gNavToolbox.childNodes[i];
  4157.     var toolbarName = toolbar.getAttribute("toolbarname");
  4158.     var type = toolbar.getAttribute("type");
  4159.     if (toolbarName && type != "menubar") {
  4160.       var menuItem = document.createElement("menuitem");
  4161.       menuItem.setAttribute("toolbarindex", i);
  4162.       menuItem.setAttribute("type", "checkbox");
  4163.       menuItem.setAttribute("label", toolbarName);
  4164.       menuItem.setAttribute("accesskey", toolbar.getAttribute("accesskey"));
  4165.       menuItem.setAttribute("checked", toolbar.getAttribute("collapsed") != "true");
  4166.       popup.insertBefore(menuItem, firstMenuItem);
  4167.  
  4168.       menuItem.addEventListener("command", onViewToolbarCommand, false);
  4169.     }
  4170.     toolbar = toolbar.nextSibling;
  4171.   }
  4172. }
  4173.  
  4174. function onViewToolbarCommand(aEvent)
  4175. {
  4176.   var index = aEvent.originalTarget.getAttribute("toolbarindex");
  4177.   var toolbar = gNavToolbox.childNodes[index];
  4178.  
  4179.   toolbar.collapsed = aEvent.originalTarget.getAttribute("checked") != "true";
  4180.   document.persist(toolbar.id, "collapsed");
  4181. }
  4182.  
  4183. function displaySecurityInfo()
  4184. {
  4185.   BrowserPageInfo(null, "securityTab");
  4186. }
  4187.  
  4188. /**
  4189.  * Opens or closes the sidebar identified by commandID.
  4190.  *
  4191.  * @param commandID a string identifying the sidebar to toggle; see the
  4192.  *                  note below. (Optional if a sidebar is already open.)
  4193.  * @param forceOpen boolean indicating whether the sidebar should be
  4194.  *                  opened regardless of its current state (optional).
  4195.  * @note
  4196.  * We expect to find a xul:broadcaster element with the specified ID.
  4197.  * The following attributes on that element may be used and/or modified:
  4198.  *  - id           (required) the string to match commandID. The convention
  4199.  *                 is to use this naming scheme: 'view<sidebar-name>Sidebar'.
  4200.  *  - sidebarurl   (required) specifies the URL to load in this sidebar.
  4201.  *  - sidebartitle or label (in that order) specify the title to 
  4202.  *                 display on the sidebar.
  4203.  *  - checked      indicates whether the sidebar is currently displayed.
  4204.  *                 Note that toggleSidebar updates this attribute when
  4205.  *                 it changes the sidebar's visibility.
  4206.  *  - group        this attribute must be set to "sidebar".
  4207.  */
  4208. function toggleSidebar(commandID, forceOpen) {
  4209.  
  4210.   var sidebarBox = document.getElementById("sidebar-box");
  4211.   if (!commandID)
  4212.     commandID = sidebarBox.getAttribute("sidebarcommand");
  4213.  
  4214.   var sidebarBroadcaster = document.getElementById(commandID);
  4215.   var sidebar = document.getElementById("sidebar"); // xul:browser
  4216.   var sidebarTitle = document.getElementById("sidebar-title");
  4217.   var sidebarSplitter = document.getElementById("sidebar-splitter");
  4218.  
  4219.   if (sidebarBroadcaster.getAttribute("checked") == "true") {
  4220.     if (!forceOpen) {
  4221.       sidebarBroadcaster.removeAttribute("checked");
  4222.       sidebarBox.setAttribute("sidebarcommand", "");
  4223.       sidebarTitle.value = "";
  4224.       sidebar.setAttribute("src", "about:blank");
  4225.       sidebarBox.hidden = true;
  4226.       sidebarSplitter.hidden = true;
  4227.       content.focus();
  4228.     } else {
  4229.       fireSidebarFocusedEvent();
  4230.     }
  4231.     return;
  4232.   }
  4233.  
  4234.   // now we need to show the specified sidebar
  4235.  
  4236.   // ..but first update the 'checked' state of all sidebar broadcasters
  4237.   var broadcasters = document.getElementsByAttribute("group", "sidebar");
  4238.   for (var i = 0; i < broadcasters.length; ++i) {
  4239.     // skip elements that observe sidebar broadcasters and random
  4240.     // other elements
  4241.     if (broadcasters[i].localName != "broadcaster")
  4242.       continue;
  4243.  
  4244.     if (broadcasters[i] != sidebarBroadcaster)
  4245.       broadcasters[i].removeAttribute("checked");
  4246.     else
  4247.       sidebarBroadcaster.setAttribute("checked", "true");
  4248.   }
  4249.  
  4250.   sidebarBox.hidden = false;
  4251.   sidebarSplitter.hidden = false;
  4252.  
  4253.   var url = sidebarBroadcaster.getAttribute("sidebarurl");
  4254.   var title = sidebarBroadcaster.getAttribute("sidebartitle");
  4255.   if (!title)
  4256.     title = sidebarBroadcaster.getAttribute("label");
  4257.   sidebar.setAttribute("src", url); // kick off async load
  4258.   sidebarBox.setAttribute("sidebarcommand", sidebarBroadcaster.id);
  4259.   sidebarTitle.value = title;
  4260.  
  4261.   // We set this attribute here in addition to setting it on the <browser>
  4262.   // element itself, because the code in BrowserShutdown persists this
  4263.   // attribute, not the "src" of the <browser id="sidebar">. The reason it
  4264.   // does that is that we want to delay sidebar load a bit when a browser
  4265.   // window opens. See delayedStartup().
  4266.   sidebarBox.setAttribute("src", url);
  4267.  
  4268.   if (sidebar.contentDocument.location.href != url)
  4269.     sidebar.addEventListener("load", sidebarOnLoad, true);
  4270.   else // older code handled this case, so we do it too
  4271.     fireSidebarFocusedEvent();
  4272. }
  4273.  
  4274. function sidebarOnLoad(event) {
  4275.   var sidebar = document.getElementById("sidebar");
  4276.   sidebar.removeEventListener("load", sidebarOnLoad, true);
  4277.   // We're handling the 'load' event before it bubbles up to the usual
  4278.   // (non-capturing) event handlers. Let it bubble up before firing the
  4279.   // SidebarFocused event.
  4280.   setTimeout(fireSidebarFocusedEvent, 0);
  4281. }
  4282.  
  4283. /**
  4284.  * Fire a "SidebarFocused" event on the sidebar's |window| to give the sidebar
  4285.  * a chance to adjust focus as needed. An additional event is needed, because
  4286.  * we don't want to focus the sidebar when it's opened on startup or in a new
  4287.  * window, only when the user opens the sidebar.
  4288.  */
  4289. function fireSidebarFocusedEvent() {
  4290.   var sidebar = document.getElementById("sidebar");
  4291.   var event = document.createEvent("Events");
  4292.   event.initEvent("SidebarFocused", true, false);
  4293.   sidebar.contentWindow.dispatchEvent(event);
  4294. }
  4295.  
  4296. var gHomeButton = {
  4297.   prefDomain: "browser.startup.homepage",
  4298.   observe: function (aSubject, aTopic, aPrefName)
  4299.   {
  4300.     if (aTopic != "nsPref:changed" || aPrefName != this.prefDomain)
  4301.       return;
  4302.  
  4303.     this.updateTooltip();
  4304.   },
  4305.  
  4306.   updateTooltip: function (homeButton)
  4307.   {
  4308.     if (!homeButton)
  4309.       homeButton = document.getElementById("home-button");
  4310.     if (homeButton) {
  4311.       var homePage = this.getHomePage();
  4312.       homePage = homePage.replace(/\|/g,', ');
  4313.       homeButton.setAttribute("tooltiptext", homePage);
  4314.     }
  4315.   },
  4316.  
  4317.   getHomePage: function ()
  4318.   {
  4319.     var url;
  4320.     try {
  4321.       url = gPrefService.getComplexValue(this.prefDomain,
  4322.                                 Components.interfaces.nsIPrefLocalizedString).data;
  4323.     } catch (e) {
  4324.     }
  4325.  
  4326.     // use this if we can't find the pref
  4327.     if (!url) {
  4328.       var SBS = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
  4329.       var configBundle = SBS.createBundle("resource:/browserconfig.properties");
  4330.       url = configBundle.GetStringFromName(this.prefDomain);
  4331.     }
  4332.  
  4333.     return url;
  4334.   },
  4335.  
  4336.   updatePersonalToolbarStyle: function (homeButton)
  4337.   {
  4338.     if (!homeButton)
  4339.       homeButton = document.getElementById("home-button");
  4340.     if (homeButton)
  4341.       homeButton.className = homeButton.parentNode.id == "PersonalToolbar"
  4342.                                || homeButton.parentNode.parentNode.id == "PersonalToolbar" ?
  4343.                              homeButton.className.replace("toolbarbutton-1", "bookmark-item") :
  4344.                              homeButton.className.replace("bookmark-item", "toolbarbutton-1");
  4345.   }
  4346. };
  4347.  
  4348. /**
  4349.  * Gets the selected text in the active browser. Leading and trailing
  4350.  * whitespace is removed, and consecutive whitespace is replaced by a single
  4351.  * space. A maximum of 150 characters will be returned, regardless of the value
  4352.  * of aCharLen.
  4353.  *
  4354.  * @param aCharLen
  4355.  *        The maximum number of characters to return.
  4356.  */
  4357. function getBrowserSelection(aCharLen) {
  4358.   // selections of more than 150 characters aren't useful
  4359.   const kMaxSelectionLen = 150;
  4360.   const charLen = Math.min(aCharLen || kMaxSelectionLen, kMaxSelectionLen);
  4361.  
  4362.   var focusedWindow = document.commandDispatcher.focusedWindow;
  4363.   var selection = focusedWindow.getSelection().toString();
  4364.  
  4365.   if (selection) {
  4366.     if (selection.length > charLen) {
  4367.       // only use the first charLen important chars. see bug 221361
  4368.       var pattern = new RegExp("^(?:\\s*.){0," + charLen + "}");
  4369.       pattern.test(selection);
  4370.       selection = RegExp.lastMatch;
  4371.     }
  4372.  
  4373.     selection = selection.replace(/^\s+/, "")
  4374.                          .replace(/\s+$/, "")
  4375.                          .replace(/\s+/g, " ");
  4376.  
  4377.     if (selection.length > charLen)
  4378.       selection = selection.substr(0, charLen);
  4379.   }
  4380.   return selection;
  4381. }
  4382.  
  4383. var gWebPanelURI;
  4384. function openWebPanel(aTitle, aURI)
  4385. {
  4386.     // Ensure that the web panels sidebar is open.
  4387.     toggleSidebar('viewWebPanelsSidebar', true);
  4388.  
  4389.     // Set the title of the panel.
  4390.     document.getElementById("sidebar-title").value = aTitle;
  4391.  
  4392.     // Tell the Web Panels sidebar to load the bookmark.
  4393.     var sidebar = document.getElementById("sidebar");
  4394.     if (sidebar.docShell && sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser')) {
  4395.         sidebar.contentWindow.loadWebPanel(aURI);
  4396.         if (gWebPanelURI) {
  4397.             gWebPanelURI = "";
  4398.             sidebar.removeEventListener("load", asyncOpenWebPanel, true);
  4399.         }
  4400.     }
  4401.     else {
  4402.         // The panel is still being constructed.  Attach an onload handler.
  4403.         if (!gWebPanelURI)
  4404.             sidebar.addEventListener("load", asyncOpenWebPanel, true);
  4405.         gWebPanelURI = aURI;
  4406.     }
  4407. }
  4408.  
  4409. function asyncOpenWebPanel(event)
  4410. {
  4411.     var sidebar = document.getElementById("sidebar");
  4412.     if (gWebPanelURI && sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser'))
  4413.         sidebar.contentWindow.loadWebPanel(gWebPanelURI);
  4414.     gWebPanelURI = "";
  4415.     sidebar.removeEventListener("load", asyncOpenWebPanel, true);
  4416. }
  4417.  
  4418. /*
  4419.  * - [ Dependencies ] ---------------------------------------------------------
  4420.  *  utilityOverlay.js:
  4421.  *    - gatherTextUnder
  4422.  */
  4423.  
  4424.  // Called whenever the user clicks in the content area,
  4425.  // except when left-clicking on links (special case)
  4426.  // should always return true for click to go through
  4427.  function contentAreaClick(event, fieldNormalClicks)
  4428.  {
  4429.    if (!event.isTrusted || event.getPreventDefault()) {
  4430.      return true;
  4431.    }
  4432.  
  4433.    var target = event.target;
  4434.    var linkNode;
  4435.  
  4436.    if (target instanceof HTMLAnchorElement ||
  4437.        target instanceof HTMLAreaElement ||
  4438.        target instanceof HTMLLinkElement) {
  4439.      if (target.hasAttribute("href"))
  4440.        linkNode = target;
  4441.  
  4442.      // xxxmpc: this is kind of a hack to work around a Gecko bug (see bug 266932)
  4443.      // we're going to walk up the DOM looking for a parent link node,
  4444.      // this shouldn't be necessary, but we're matching the existing behaviour for left click
  4445.      var parent = target.parentNode;
  4446.      while (parent) {
  4447.        if (parent instanceof HTMLAnchorElement ||
  4448.            parent instanceof HTMLAreaElement ||
  4449.            parent instanceof HTMLLinkElement) {
  4450.            if (parent.hasAttribute("href"))
  4451.              linkNode = parent;
  4452.        }
  4453.        parent = parent.parentNode;
  4454.      }
  4455.    }
  4456.    else {
  4457.      linkNode = event.originalTarget;
  4458.      while (linkNode && !(linkNode instanceof HTMLAnchorElement))
  4459.        linkNode = linkNode.parentNode;
  4460.      // <a> cannot be nested.  So if we find an anchor without an
  4461.      // href, there is no useful <a> around the target
  4462.      if (linkNode && !linkNode.hasAttribute("href"))
  4463.        linkNode = null;
  4464.    }
  4465.    var wrapper = null;
  4466.    if (linkNode) {
  4467.      wrapper = linkNode;
  4468.      if (event.button == 0 && !event.ctrlKey && !event.shiftKey &&
  4469.          !event.altKey && !event.metaKey) {
  4470.        // A Web panel's links should target the main content area.  Do this
  4471.        // if no modifier keys are down and if there's no target or the target equals
  4472.        // _main (the IE convention) or _content (the Mozilla convention).
  4473.        // XXX Now that markLinkVisited is gone, we may not need to field _main and
  4474.        // _content here.
  4475.        target = wrapper.getAttribute("target");
  4476.        if (fieldNormalClicks &&
  4477.            (!target || target == "_content" || target  == "_main"))
  4478.          // IE uses _main, SeaMonkey uses _content, we support both
  4479.        {
  4480.          if (!wrapper.href)
  4481.            return true;
  4482.          if (wrapper.getAttribute("onclick"))
  4483.            return true;
  4484.          // javascript links should be executed in the current browser
  4485.          if (wrapper.href.substr(0, 11) === "javascript:")
  4486.            return true;
  4487.          // data links should be executed in the current browser
  4488.          if (wrapper.href.substr(0, 5) === "data:")
  4489.            return true;
  4490.  
  4491.          try {
  4492.            urlSecurityCheck(wrapper.href, wrapper.ownerDocument.nodePrincipal);
  4493.          }
  4494.          catch(ex) {
  4495.            return false;
  4496.          } 
  4497.  
  4498.          var postData = { };
  4499.          var url = getShortcutOrURI(wrapper.href, postData);
  4500.          if (!url)
  4501.            return true;
  4502.          loadURI(url, null, postData.value, false);
  4503.          event.preventDefault();
  4504.          return false;
  4505.        }
  4506.        else if (linkNode.getAttribute("rel") == "sidebar") {
  4507.          // This is the Opera convention for a special link that - when clicked - allows
  4508.          // you to add a sidebar panel.  We support the Opera convention here.  The link's
  4509.          // title attribute contains the title that should be used for the sidebar panel.
  4510.          PlacesUIUtils.showMinimalAddBookmarkUI(makeURI(wrapper.href),
  4511.                                                 wrapper.getAttribute("title"),
  4512.                                                 null, null, true, true);
  4513.          event.preventDefault();
  4514.          return false;
  4515.        }
  4516.      }
  4517.      else {
  4518.        handleLinkClick(event, wrapper.href, linkNode);
  4519.      }
  4520.  
  4521.      return true;
  4522.    } else {
  4523.      // Try simple XLink
  4524.      var href, realHref, baseURI;
  4525.      linkNode = target;
  4526.      while (linkNode) {
  4527.        if (linkNode.nodeType == Node.ELEMENT_NODE) {
  4528.          wrapper = linkNode;
  4529.  
  4530.          realHref = wrapper.getAttributeNS("http://www.w3.org/1999/xlink", "href");
  4531.          if (realHref) {
  4532.            href = realHref;
  4533.            baseURI = wrapper.baseURI
  4534.          }
  4535.        }
  4536.        linkNode = linkNode.parentNode;
  4537.      }
  4538.      if (href) {
  4539.        href = makeURLAbsolute(baseURI, href);
  4540.        handleLinkClick(event, href, null);
  4541.        return true;
  4542.      }
  4543.    }
  4544.    if (event.button == 1 &&
  4545.        gPrefService.getBoolPref("middlemouse.contentLoadURL") &&
  4546.        !gPrefService.getBoolPref("general.autoScroll")) {
  4547.      middleMousePaste(event);
  4548.    }
  4549.    return true;
  4550.  }
  4551.  
  4552. function handleLinkClick(event, href, linkNode)
  4553. {
  4554.   var doc = event.target.ownerDocument;
  4555.  
  4556.   switch (event.button) {
  4557.     case 0:    // if left button clicked
  4558. //@line 4939 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  4559.       if (event.ctrlKey) {
  4560. //@line 4941 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  4561.         openNewTabWith(href, doc, null, event, false);
  4562.         event.stopPropagation();
  4563.         return true;
  4564.       }
  4565.  
  4566.       if (event.shiftKey && event.altKey) {
  4567.         var feedService = 
  4568.             Cc["@mozilla.org/browser/feeds/result-service;1"].
  4569.             getService(Ci.nsIFeedResultService);
  4570.         feedService.forcePreviewPage = true;
  4571.         loadURI(href, null, null, false);
  4572.         return false;
  4573.       }
  4574.                                                        
  4575.       if (event.shiftKey) {
  4576.         openNewWindowWith(href, doc, null, false);
  4577.         event.stopPropagation();
  4578.         return true;
  4579.       }
  4580.  
  4581.       if (event.altKey) {
  4582.         saveURL(href, linkNode ? gatherTextUnder(linkNode) : "", null, true,
  4583.                 true, doc.documentURIObject);
  4584.         return true;
  4585.       }
  4586.  
  4587.       return false;
  4588.     case 1:    // if middle button clicked
  4589.       var tab;
  4590.       try {
  4591.         tab = gPrefService.getBoolPref("browser.tabs.opentabfor.middleclick")
  4592.       }
  4593.       catch(ex) {
  4594.         tab = true;
  4595.       }
  4596.       if (tab)
  4597.         openNewTabWith(href, doc, null, event, false);
  4598.       else
  4599.         openNewWindowWith(href, doc, null, false);
  4600.       event.stopPropagation();
  4601.       return true;
  4602.   }
  4603.   return false;
  4604. }
  4605.  
  4606. function middleMousePaste(event)
  4607. {
  4608.   var url = readFromClipboard();
  4609.   if (!url)
  4610.     return;
  4611.  
  4612.   var postData = { };
  4613.   url = getShortcutOrURI(url, postData);
  4614.   if (!url)
  4615.     return;
  4616.  
  4617.   try {
  4618.     addToUrlbarHistory(url);
  4619.   } catch (ex) {
  4620.     // Things may go wrong when adding url to session history,
  4621.     // but don't let that interfere with the loading of the url.
  4622.     Cu.reportError(ex);
  4623.   }
  4624.  
  4625.   openUILink(url,
  4626.              event,
  4627.              true /* ignore the fact this is a middle click */);
  4628.  
  4629.   event.stopPropagation();
  4630. }
  4631.  
  4632. /*
  4633.  * Note that most of this routine has been moved into C++ in order to
  4634.  * be available for all <browser> tags as well as gecko embedding. See
  4635.  * mozilla/content/base/src/nsContentAreaDragDrop.cpp.
  4636.  *
  4637.  * Do not add any new fuctionality here other than what is needed for
  4638.  * a standalone product.
  4639.  */
  4640.  
  4641. var contentAreaDNDObserver = {
  4642.   onDrop: function (aEvent, aXferData, aDragSession)
  4643.     {
  4644.       if (aEvent.getPreventDefault())
  4645.         return;
  4646.  
  4647.       var dragType = aXferData.flavour.contentType;
  4648.       var dragData = aXferData.data;
  4649.  
  4650.       var url = transferUtils.retrieveURLFromData(dragData, dragType);
  4651.  
  4652.       // valid urls don't contain spaces ' '; if we have a space it
  4653.       // isn't a valid url, or if it's a javascript: or data: url,
  4654.       // bail out
  4655.       if (!url || !url.length || url.indexOf(" ", 0) != -1 ||
  4656.           /^\s*(javascript|data):/.test(url))
  4657.         return;
  4658.  
  4659.       nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  4660.  
  4661.       switch (document.documentElement.getAttribute('windowtype')) {
  4662.         case "navigator:browser":
  4663.           var postData = { };
  4664.           var uri = getShortcutOrURI(url, postData);
  4665.           loadURI(uri, null, postData.value, false);
  4666.           break;
  4667.         case "navigator:view-source":
  4668.           viewSource(url);
  4669.           break;
  4670.       }
  4671.  
  4672.       // keep the event from being handled by the dragDrop listeners
  4673.       // built-in to gecko if they happen to be above us.
  4674.       aEvent.preventDefault();
  4675.     },
  4676.  
  4677.   getSupportedFlavours: function ()
  4678.     {
  4679.       var flavourSet = new FlavourSet();
  4680.       flavourSet.appendFlavour(TAB_DROP_TYPE);
  4681.       flavourSet.appendFlavour("text/x-moz-url");
  4682.       flavourSet.appendFlavour("text/plain");
  4683.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  4684.       return flavourSet;
  4685.     }
  4686.  
  4687. };
  4688.  
  4689. function MultiplexHandler(event)
  4690. { try {
  4691.     var node = event.target;
  4692.     var name = node.getAttribute('name');
  4693.  
  4694.     if (name == 'detectorGroup') {
  4695.         SetForcedDetector(true);
  4696.         SelectDetector(event, false);
  4697.     } else if (name == 'charsetGroup') {
  4698.         var charset = node.getAttribute('id');
  4699.         charset = charset.substring('charset.'.length, charset.length)
  4700.         SetForcedCharset(charset);
  4701.     } else if (name == 'charsetCustomize') {
  4702.         //do nothing - please remove this else statement, once the charset prefs moves to the pref window
  4703.     } else {
  4704.         SetForcedCharset(node.getAttribute('id'));
  4705.     }
  4706.     } catch(ex) { alert(ex); }
  4707. }
  4708.  
  4709. function SelectDetector(event, doReload)
  4710. {
  4711.     var uri =  event.target.getAttribute("id");
  4712.     var prefvalue = uri.substring('chardet.'.length, uri.length);
  4713.     if ("off" == prefvalue) { // "off" is special value to turn off the detectors
  4714.         prefvalue = "";
  4715.     }
  4716.  
  4717.     try {
  4718.         var pref = Components.classes["@mozilla.org/preferences-service;1"]
  4719.                              .getService(Components.interfaces.nsIPrefBranch);
  4720.         var str =  Components.classes["@mozilla.org/supports-string;1"]
  4721.                              .createInstance(Components.interfaces.nsISupportsString);
  4722.  
  4723.         str.data = prefvalue;
  4724.         pref.setComplexValue("intl.charset.detector",
  4725.                              Components.interfaces.nsISupportsString, str);
  4726.         if (doReload) window.content.location.reload();
  4727.     }
  4728.     catch (ex) {
  4729.         dump("Failed to set the intl.charset.detector preference.\n");
  4730.     }
  4731. }
  4732.  
  4733. function SetForcedDetector(doReload)
  4734. {
  4735.     BrowserSetForcedDetector(doReload);
  4736. }
  4737.  
  4738. function SetForcedCharset(charset)
  4739. {
  4740.     BrowserSetForcedCharacterSet(charset);
  4741. }
  4742.  
  4743. function BrowserSetForcedCharacterSet(aCharset)
  4744. {
  4745.   var docCharset = gBrowser.docShell.QueryInterface(Ci.nsIDocCharset);
  4746.   docCharset.charset = aCharset;
  4747.   // Save the forced character-set
  4748.   PlacesUtils.history.setCharsetForURI(getWebNavigation().currentURI, aCharset);
  4749.   BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
  4750. }
  4751.  
  4752. function BrowserSetForcedDetector(doReload)
  4753. {
  4754.   gBrowser.documentCharsetInfo.forcedDetector = true;
  4755.   if (doReload)
  4756.     BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
  4757. }
  4758.  
  4759. function UpdateCurrentCharset()
  4760. {
  4761.     // extract the charset from DOM
  4762.     var wnd = document.commandDispatcher.focusedWindow;
  4763.     if ((window == wnd) || (wnd == null)) wnd = window.content;
  4764.  
  4765.     // Uncheck previous item
  4766.     if (gPrevCharset) {
  4767.         var pref_item = document.getElementById('charset.' + gPrevCharset);
  4768.         if (pref_item)
  4769.           pref_item.setAttribute('checked', 'false');
  4770.     }
  4771.  
  4772.     var menuitem = document.getElementById('charset.' + wnd.document.characterSet);
  4773.     if (menuitem) {
  4774.         menuitem.setAttribute('checked', 'true');
  4775.     }
  4776. }
  4777.  
  4778. function UpdateCharsetDetector()
  4779. {
  4780.     var prefvalue;
  4781.  
  4782.     try {
  4783.         var pref = Components.classes["@mozilla.org/preferences-service;1"]
  4784.                              .getService(Components.interfaces.nsIPrefBranch);
  4785.         prefvalue = pref.getComplexValue("intl.charset.detector",
  4786.                                          Components.interfaces.nsIPrefLocalizedString).data;
  4787.     }
  4788.     catch (ex) {
  4789.         prefvalue = "";
  4790.     }
  4791.  
  4792.     if (prefvalue == "") prefvalue = "off";
  4793.     dump("intl.charset.detector = "+ prefvalue + "\n");
  4794.  
  4795.     prefvalue = 'chardet.' + prefvalue;
  4796.     var menuitem = document.getElementById(prefvalue);
  4797.  
  4798.     if (menuitem) {
  4799.         menuitem.setAttribute('checked', 'true');
  4800.     }
  4801. }
  4802.  
  4803. function UpdateMenus(event)
  4804. {
  4805.     // use setTimeout workaround to delay checkmark the menu
  4806.     // when onmenucomplete is ready then use it instead of oncreate
  4807.     // see bug 78290 for the detail
  4808.     UpdateCurrentCharset();
  4809.     setTimeout(UpdateCurrentCharset, 0);
  4810.     UpdateCharsetDetector();
  4811.     setTimeout(UpdateCharsetDetector, 0);
  4812. }
  4813.  
  4814. function CreateMenu(node)
  4815. {
  4816.   var observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4817.   observerService.notifyObservers(null, "charsetmenu-selected", node);
  4818. }
  4819.  
  4820. function charsetLoadListener (event)
  4821. {
  4822.     var charset = window.content.document.characterSet;
  4823.  
  4824.     if (charset.length > 0 && (charset != gLastBrowserCharset)) {
  4825.         if (!gCharsetMenu)
  4826.           gCharsetMenu = Components.classes['@mozilla.org/rdf/datasource;1?name=charset-menu'].getService().QueryInterface(Components.interfaces.nsICurrentCharsetListener);
  4827.         gCharsetMenu.SetCurrentCharset(charset);
  4828.         gPrevCharset = gLastBrowserCharset;
  4829.         gLastBrowserCharset = charset;
  4830.     }
  4831. }
  4832.  
  4833. /* Begin Page Style Functions */
  4834. function getAllStyleSheets(frameset) {
  4835.   var styleSheetsArray = Array.slice(frameset.document.styleSheets);
  4836.   for (let i = 0; i < frameset.frames.length; i++) {
  4837.     let frameSheets = getAllStyleSheets(frameset.frames[i]);
  4838.     styleSheetsArray = styleSheetsArray.concat(frameSheets);
  4839.   }
  4840.   return styleSheetsArray;
  4841. }
  4842.  
  4843. function stylesheetFillPopup(menuPopup) {
  4844.   var noStyle = menuPopup.firstChild;
  4845.   var persistentOnly = noStyle.nextSibling;
  4846.   var sep = persistentOnly.nextSibling;
  4847.   while (sep.nextSibling)
  4848.     menuPopup.removeChild(sep.nextSibling);
  4849.  
  4850.   var styleSheets = getAllStyleSheets(window.content);
  4851.   var currentStyleSheets = {};
  4852.   var styleDisabled = getMarkupDocumentViewer().authorStyleDisabled;
  4853.   var haveAltSheets = false;
  4854.   var altStyleSelected = false;
  4855.  
  4856.   for (let i = 0; i < styleSheets.length; ++i) {
  4857.     let currentStyleSheet = styleSheets[i];
  4858.  
  4859.     if (!currentStyleSheet.title)
  4860.       continue;
  4861.  
  4862.     // Skip any stylesheets that don't match the screen media type.
  4863.     let (media = currentStyleSheet.media.mediaText.toLowerCase()) {
  4864.       if (media && (media.indexOf("screen") == -1) && (media.indexOf("all") == -1))
  4865.         continue;
  4866.     }
  4867.  
  4868.     if (!currentStyleSheet.disabled)
  4869.       altStyleSelected = true;
  4870.  
  4871.     haveAltSheets = true;
  4872.  
  4873.     let lastWithSameTitle = null;
  4874.     if (currentStyleSheet.title in currentStyleSheets)
  4875.       lastWithSameTitle = currentStyleSheets[currentStyleSheet.title];
  4876.  
  4877.     if (!lastWithSameTitle) {
  4878.       let menuItem = document.createElement("menuitem");
  4879.       menuItem.setAttribute("type", "radio");
  4880.       menuItem.setAttribute("label", currentStyleSheet.title);
  4881.       menuItem.setAttribute("data", currentStyleSheet.title);
  4882.       menuItem.setAttribute("checked", !currentStyleSheet.disabled && !styleDisabled);
  4883.       menuPopup.appendChild(menuItem);
  4884.       currentStyleSheets[currentStyleSheet.title] = menuItem;
  4885.     } else if (currentStyleSheet.disabled) {
  4886.       lastWithSameTitle.removeAttribute("checked");
  4887.     }
  4888.   }
  4889.  
  4890.   noStyle.setAttribute("checked", styleDisabled);
  4891.   persistentOnly.setAttribute("checked", !altStyleSelected && !styleDisabled);
  4892.   persistentOnly.hidden = (window.content.document.preferredStyleSheetSet) ? haveAltSheets : false;
  4893.   sep.hidden = (noStyle.hidden && persistentOnly.hidden) || !haveAltSheets;
  4894.   return true;
  4895. }
  4896.  
  4897. function stylesheetInFrame(frame, title) {
  4898.   return Array.some(frame.document.styleSheets,
  4899.                     function (stylesheet) stylesheet.title == title);
  4900. }
  4901.  
  4902. function stylesheetSwitchFrame(frame, title) {
  4903.   var docStyleSheets = frame.document.styleSheets;
  4904.  
  4905.   for (let i = 0; i < docStyleSheets.length; ++i) {
  4906.     let docStyleSheet = docStyleSheets[i];
  4907.  
  4908.     if (title == "_nostyle")
  4909.       docStyleSheet.disabled = true;
  4910.     else if (docStyleSheet.title)
  4911.       docStyleSheet.disabled = (docStyleSheet.title != title);
  4912.     else if (docStyleSheet.disabled)
  4913.       docStyleSheet.disabled = false;
  4914.   }
  4915. }
  4916.  
  4917. function stylesheetSwitchAll(frameset, title) {
  4918.   if (!title || title == "_nostyle" || stylesheetInFrame(frameset, title))
  4919.     stylesheetSwitchFrame(frameset, title);
  4920.  
  4921.   for (let i = 0; i < frameset.frames.length; i++)
  4922.     stylesheetSwitchAll(frameset.frames[i], title);
  4923. }
  4924.  
  4925. function setStyleDisabled(disabled) {
  4926.   getMarkupDocumentViewer().authorStyleDisabled = disabled;
  4927. }
  4928. /* End of the Page Style functions */
  4929.  
  4930. var BrowserOffline = {
  4931.   /////////////////////////////////////////////////////////////////////////////
  4932.   // BrowserOffline Public Methods
  4933.   init: function ()
  4934.   {
  4935.     if (!this._uiElement)
  4936.       this._uiElement = document.getElementById("goOfflineMenuitem");
  4937.  
  4938.     var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4939.     os.addObserver(this, "network:offline-status-changed", false);
  4940.  
  4941.     var ioService = Components.classes["@mozilla.org/network/io-service;1"].
  4942.       getService(Components.interfaces.nsIIOService2);
  4943.  
  4944.     // if ioService is managing the offline status, then ioservice.offline
  4945.     // is already set correctly. We will continue to allow the ioService
  4946.     // to manage its offline state until the user uses the "Work Offline" UI.
  4947.     
  4948.     if (!ioService.manageOfflineStatus) {
  4949.       // set the initial state
  4950.       var isOffline = false;
  4951.       try {
  4952.         isOffline = gPrefService.getBoolPref("browser.offline");
  4953.       }
  4954.       catch (e) { }
  4955.       ioService.offline = isOffline;
  4956.     }
  4957.     
  4958.     this._updateOfflineUI(ioService.offline);
  4959.   },
  4960.  
  4961.   uninit: function ()
  4962.   {
  4963.     try {
  4964.       var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4965.       os.removeObserver(this, "network:offline-status-changed");
  4966.     } catch (ex) {
  4967.     }
  4968.   },
  4969.  
  4970.   toggleOfflineStatus: function ()
  4971.   {
  4972.     var ioService = Components.classes["@mozilla.org/network/io-service;1"].
  4973.       getService(Components.interfaces.nsIIOService2);
  4974.  
  4975.     // Stop automatic management of the offline status
  4976.     try {
  4977.       ioService.manageOfflineStatus = false;
  4978.     } catch (ex) {
  4979.     }
  4980.   
  4981.     if (!ioService.offline && !this._canGoOffline()) {
  4982.       this._updateOfflineUI(false);
  4983.       return;
  4984.     }
  4985.  
  4986.     ioService.offline = !ioService.offline;
  4987.  
  4988.     // Save the current state for later use as the initial state
  4989.     // (if there is no netLinkService)
  4990.     gPrefService.setBoolPref("browser.offline", ioService.offline);
  4991.   },
  4992.  
  4993.   /////////////////////////////////////////////////////////////////////////////
  4994.   // nsIObserver
  4995.   observe: function (aSubject, aTopic, aState)
  4996.   {
  4997.     if (aTopic != "network:offline-status-changed")
  4998.       return;
  4999.  
  5000.     this._updateOfflineUI(aState == "offline");
  5001.   },
  5002.  
  5003.   /////////////////////////////////////////////////////////////////////////////
  5004.   // BrowserOffline Implementation Methods
  5005.   _canGoOffline: function ()
  5006.   {
  5007.     var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  5008.     if (os) {
  5009.       try {
  5010.         var cancelGoOffline = Components.classes["@mozilla.org/supports-PRBool;1"].createInstance(Components.interfaces.nsISupportsPRBool);
  5011.         os.notifyObservers(cancelGoOffline, "offline-requested", null);
  5012.  
  5013.         // Something aborted the quit process.
  5014.         if (cancelGoOffline.data)
  5015.           return false;
  5016.       }
  5017.       catch (ex) {
  5018.       }
  5019.     }
  5020.     return true;
  5021.   },
  5022.  
  5023.   _uiElement: null,
  5024.   _updateOfflineUI: function (aOffline)
  5025.   {
  5026.     var offlineLocked = gPrefService.prefIsLocked("network.online");
  5027.     if (offlineLocked)
  5028.       this._uiElement.setAttribute("disabled", "true");
  5029.  
  5030.     this._uiElement.setAttribute("checked", aOffline);
  5031.   }
  5032. };
  5033.  
  5034. var OfflineApps = {
  5035.   /////////////////////////////////////////////////////////////////////////////
  5036.   // OfflineApps Public Methods
  5037.   init: function ()
  5038.   {
  5039.     var obs = Cc["@mozilla.org/observer-service;1"].
  5040.               getService(Ci.nsIObserverService);
  5041.     obs.addObserver(this, "dom-storage-warn-quota-exceeded", false);
  5042.     obs.addObserver(this, "offline-cache-update-completed", false);
  5043.   },
  5044.  
  5045.   uninit: function ()
  5046.   {
  5047.     var obs = Cc["@mozilla.org/observer-service;1"].
  5048.               getService(Ci.nsIObserverService);
  5049.     obs.removeObserver(this, "dom-storage-warn-quota-exceeded");
  5050.     obs.removeObserver(this, "offline-cache-update-completed");
  5051.   },
  5052.  
  5053.   handleEvent: function(event) {
  5054.     if (event.type == "MozApplicationManifest") {
  5055.       this.offlineAppRequested(event.originalTarget.defaultView);
  5056.     }
  5057.   },
  5058.  
  5059.   /////////////////////////////////////////////////////////////////////////////
  5060.   // OfflineApps Implementation Methods
  5061.  
  5062.   // XXX: _getBrowserWindowForContentWindow and _getBrowserForContentWindow
  5063.   // were taken from browser/components/feeds/src/WebContentConverter.
  5064.   _getBrowserWindowForContentWindow: function(aContentWindow) {
  5065.     return aContentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  5066.                          .getInterface(Ci.nsIWebNavigation)
  5067.                          .QueryInterface(Ci.nsIDocShellTreeItem)
  5068.                          .rootTreeItem
  5069.                          .QueryInterface(Ci.nsIInterfaceRequestor)
  5070.                          .getInterface(Ci.nsIDOMWindow)
  5071.                          .wrappedJSObject;
  5072.   },
  5073.  
  5074.   _getBrowserForContentWindow: function(aBrowserWindow, aContentWindow) {
  5075.     // This depends on pseudo APIs of browser.js and tabbrowser.xml
  5076.     aContentWindow = aContentWindow.top;
  5077.     var browsers = aBrowserWindow.getBrowser().browsers;
  5078.     for (var i = 0; i < browsers.length; ++i) {
  5079.       if (browsers[i].contentWindow == aContentWindow)
  5080.         return browsers[i];
  5081.     }
  5082.   },
  5083.  
  5084.   _getManifestURI: function(aWindow) {
  5085.     if (!aWindow.document.documentElement) return null;
  5086.     var attr = aWindow.document.documentElement.getAttribute("manifest");
  5087.     if (!attr) return null;
  5088.  
  5089.     try {
  5090.       var ios = Cc["@mozilla.org/network/io-service;1"].
  5091.                 getService(Ci.nsIIOService);
  5092.  
  5093.       var contentURI = ios.newURI(aWindow.location.href, null, null);
  5094.       return ios.newURI(attr, aWindow.document.characterSet, contentURI);
  5095.     } catch (e) {
  5096.       return null;
  5097.     }
  5098.   },
  5099.  
  5100.   // A cache update isn't tied to a specific window.  Try to find
  5101.   // the best browser in which to warn the user about space usage
  5102.   _getBrowserForCacheUpdate: function(aCacheUpdate) {
  5103.     // Prefer the current browser
  5104.     var uri = this._getManifestURI(gBrowser.mCurrentBrowser.contentWindow);
  5105.     if (uri && uri.equals(aCacheUpdate.manifestURI)) {
  5106.       return gBrowser.mCurrentBrowser;
  5107.     }
  5108.  
  5109.     var browsers = gBrowser.browsers;
  5110.     for (var i = 0; i < browsers.length; ++i) {
  5111.       uri = this._getManifestURI(browsers[i].contentWindow);
  5112.       if (uri && uri.equals(aCacheUpdate.manifestURI)) {
  5113.         return browsers[i];
  5114.       }
  5115.     }
  5116.  
  5117.     return null;
  5118.   },
  5119.  
  5120.   _warnUsage: function(aBrowser, aURI) {
  5121.     if (!aBrowser)
  5122.       return;
  5123.  
  5124.     var notificationBox = gBrowser.getNotificationBox(aBrowser);
  5125.     var notification = notificationBox.getNotificationWithValue("offline-app-usage");
  5126.     if (!notification) {
  5127.       var bundle_browser = document.getElementById("bundle_browser");
  5128.  
  5129.       var buttons = [{
  5130.           label: bundle_browser.getString("offlineApps.manageUsage"),
  5131.           accessKey: bundle_browser.getString("offlineApps.manageUsageAccessKey"),
  5132.           callback: OfflineApps.manage
  5133.         }];
  5134.  
  5135.       var warnQuota = gPrefService.getIntPref("offline-apps.quota.warn");
  5136.       const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  5137.       var message = bundle_browser.getFormattedString("offlineApps.usage",
  5138.                                                       [ aURI.host,
  5139.                                                         warnQuota / 1024 ]);
  5140.  
  5141.       notificationBox.appendNotification(message, "offline-app-usage",
  5142.                                          "chrome://browser/skin/Info.png",
  5143.                                          priority, buttons);
  5144.     }
  5145.  
  5146.     // Now that we've warned once, prevent the warning from showing up
  5147.     // again.
  5148.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5149.              getService(Ci.nsIPermissionManager);
  5150.     pm.add(aURI, "offline-app",
  5151.            Ci.nsIOfflineCacheUpdateService.ALLOW_NO_WARN);
  5152.   },
  5153.  
  5154.   // XXX: duplicated in preferences/advanced.js
  5155.   _getOfflineAppUsage: function (host, groups)
  5156.   {
  5157.     var cacheService = Components.classes["@mozilla.org/network/application-cache-service;1"].
  5158.                        getService(Components.interfaces.nsIApplicationCacheService);
  5159.     if (!groups) {
  5160.       groups = cacheService.getGroups({});
  5161.     }
  5162.     var ios = Components.classes["@mozilla.org/network/io-service;1"].
  5163.               getService(Components.interfaces.nsIIOService);
  5164.  
  5165.     var usage = 0;
  5166.     for (var i = 0; i < groups.length; i++) {
  5167.       var uri = ios.newURI(groups[i], null, null);
  5168.       if (uri.asciiHost == host) {
  5169.         var cache = cacheService.getActiveCache(groups[i]);
  5170.         usage += cache.usage;
  5171.       }
  5172.     }
  5173.  
  5174.     var storageManager = Components.classes["@mozilla.org/dom/storagemanager;1"].
  5175.                          getService(Components.interfaces.nsIDOMStorageManager);
  5176.     usage += storageManager.getUsage(host);
  5177.  
  5178.     return usage;
  5179.   },
  5180.  
  5181.   _checkUsage: function(aURI) {
  5182.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5183.              getService(Ci.nsIPermissionManager);
  5184.  
  5185.     // if the user has already allowed excessive usage, don't bother checking
  5186.     if (pm.testExactPermission(aURI, "offline-app") !=
  5187.         Ci.nsIOfflineCacheUpdateService.ALLOW_NO_WARN) {
  5188.       var usage = this._getOfflineAppUsage(aURI.asciiHost);
  5189.       var warnQuota = gPrefService.getIntPref("offline-apps.quota.warn");
  5190.       if (usage >= warnQuota * 1024) {
  5191.         return true;
  5192.       }
  5193.     }
  5194.  
  5195.     return false;
  5196.   },
  5197.  
  5198.   offlineAppRequested: function(aContentWindow) {
  5199.     if (!gPrefService.getBoolPref("browser.offline-apps.notify")) {
  5200.       return;
  5201.     }
  5202.  
  5203.     var browserWindow = this._getBrowserWindowForContentWindow(aContentWindow);
  5204.     var browser = this._getBrowserForContentWindow(browserWindow,
  5205.                                                    aContentWindow);
  5206.  
  5207.     var currentURI = aContentWindow.document.documentURIObject;
  5208.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5209.              getService(Ci.nsIPermissionManager);
  5210.  
  5211.     // don't bother showing UI if the user has already made a decision
  5212.     if (pm.testExactPermission(currentURI, "offline-app") !=
  5213.         Ci.nsIPermissionManager.UNKNOWN_ACTION)
  5214.       return;
  5215.  
  5216.     try {
  5217.       if (gPrefService.getBoolPref("offline-apps.allow_by_default")) {
  5218.         // all pages can use offline capabilities, no need to ask the user
  5219.         return;
  5220.       }
  5221.     } catch(e) {
  5222.       // this pref isn't set by default, ignore failures
  5223.     }
  5224.  
  5225.     var host = currentURI.asciiHost;
  5226.     var notificationBox = gBrowser.getNotificationBox(browser);
  5227.     var notificationID = "offline-app-requested-" + host;
  5228.     var notification = notificationBox.getNotificationWithValue(notificationID);
  5229.  
  5230.     if (notification) {
  5231.       notification.documents.push(aContentWindow.document);
  5232.     } else {
  5233.       var bundle_browser = document.getElementById("bundle_browser");
  5234.  
  5235.       var buttons = [{
  5236.         label: bundle_browser.getString("offlineApps.allow"),
  5237.         accessKey: bundle_browser.getString("offlineApps.allowAccessKey"),
  5238.         callback: function() {
  5239.           for (var i = 0; i < notification.documents.length; i++) {
  5240.             OfflineApps.allowSite(notification.documents[i]);
  5241.           }
  5242.         }
  5243.       },{
  5244.         label: bundle_browser.getString("offlineApps.never"),
  5245.         accessKey: bundle_browser.getString("offlineApps.neverAccessKey"),
  5246.         callback: function() {
  5247.           for (var i = 0; i < notification.documents.length; i++) {
  5248.             OfflineApps.disallowSite(notification.documents[i]);
  5249.           }
  5250.         }
  5251.       },{
  5252.         label: bundle_browser.getString("offlineApps.notNow"),
  5253.         accessKey: bundle_browser.getString("offlineApps.notNowAccessKey"),
  5254.         callback: function() { /* noop */ }
  5255.       }];
  5256.  
  5257.       const priority = notificationBox.PRIORITY_INFO_LOW;
  5258.       var message = bundle_browser.getFormattedString("offlineApps.available",
  5259.                                                       [ host ]);
  5260.       notification =
  5261.         notificationBox.appendNotification(message, notificationID,
  5262.                                            "chrome://browser/skin/Info.png",
  5263.                                            priority, buttons);
  5264.       notification.documents = [ aContentWindow.document ];
  5265.     }
  5266.   },
  5267.  
  5268.   allowSite: function(aDocument) {
  5269.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5270.              getService(Ci.nsIPermissionManager);
  5271.     pm.add(aDocument.documentURIObject, "offline-app",
  5272.            Ci.nsIPermissionManager.ALLOW_ACTION);
  5273.  
  5274.     // When a site is enabled while loading, manifest resources will
  5275.     // start fetching immediately.  This one time we need to do it
  5276.     // ourselves.
  5277.     this._startFetching(aDocument);
  5278.   },
  5279.  
  5280.   disallowSite: function(aDocument) {
  5281.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5282.              getService(Ci.nsIPermissionManager);
  5283.     pm.add(aDocument.documentURIObject, "offline-app",
  5284.            Ci.nsIPermissionManager.DENY_ACTION);
  5285.   },
  5286.  
  5287.   manage: function() {
  5288.     openAdvancedPreferences("networkTab");
  5289.   },
  5290.  
  5291.   _startFetching: function(aDocument) {
  5292.     if (!aDocument.documentElement)
  5293.       return;
  5294.  
  5295.     var manifest = aDocument.documentElement.getAttribute("manifest");
  5296.     if (!manifest)
  5297.       return;
  5298.  
  5299.     var ios = Cc["@mozilla.org/network/io-service;1"].
  5300.               getService(Ci.nsIIOService);
  5301.  
  5302.     var manifestURI = ios.newURI(manifest, aDocument.characterSet,
  5303.                                  aDocument.documentURIObject);
  5304.  
  5305.     var updateService = Cc["@mozilla.org/offlinecacheupdate-service;1"].
  5306.                         getService(Ci.nsIOfflineCacheUpdateService);
  5307.     updateService.scheduleUpdate(manifestURI, aDocument.documentURIObject);
  5308.   },
  5309.  
  5310.   /////////////////////////////////////////////////////////////////////////////
  5311.   // nsIObserver
  5312.   observe: function (aSubject, aTopic, aState)
  5313.   {
  5314.     if (aTopic == "dom-storage-warn-quota-exceeded") {
  5315.       if (aSubject) {
  5316.         var uri = Cc["@mozilla.org/network/io-service;1"].
  5317.                   getService(Ci.nsIIOService).
  5318.                   newURI(aSubject.location.href, null, null);
  5319.  
  5320.         if (OfflineApps._checkUsage(uri)) {
  5321.           var browserWindow =
  5322.             this._getBrowserWindowForContentWindow(aSubject);
  5323.           var browser = this._getBrowserForContentWindow(browserWindow,
  5324.                                                          aSubject);
  5325.           OfflineApps._warnUsage(browser, uri);
  5326.         }
  5327.       }
  5328.     } else if (aTopic == "offline-cache-update-completed") {
  5329.       var cacheUpdate = aSubject.QueryInterface(Ci.nsIOfflineCacheUpdate);
  5330.  
  5331.       var uri = cacheUpdate.manifestURI;
  5332.       if (OfflineApps._checkUsage(uri)) {
  5333.         var browser = this._getBrowserForCacheUpdate(cacheUpdate);
  5334.         if (browser) {
  5335.           OfflineApps._warnUsage(browser, cacheUpdate.manifestURI);
  5336.         }
  5337.       }
  5338.     }
  5339.   }
  5340. };
  5341.  
  5342. function WindowIsClosing()
  5343. {
  5344.   var cn = gBrowser.tabContainer.childNodes;
  5345.   var numtabs = cn.length;
  5346.   var reallyClose = 
  5347.     closeWindow(false,
  5348.                 function () {
  5349.                   return gBrowser.warnAboutClosingTabs(true);
  5350.                 });
  5351.  
  5352.   if (!reallyClose)
  5353.     return false;
  5354.  
  5355.   for (var i = 0; reallyClose && i < numtabs; ++i) {
  5356.     var ds = gBrowser.getBrowserForTab(cn[i]).docShell;
  5357.  
  5358.     if (ds.contentViewer && !ds.contentViewer.permitUnload())
  5359.       reallyClose = false;
  5360.   }
  5361.  
  5362.   return reallyClose;
  5363. }
  5364.  
  5365. var MailIntegration = {
  5366.   sendLinkForWindow: function (aWindow) {
  5367.     this.sendMessage(aWindow.location.href,
  5368.                      aWindow.document.title);
  5369.   },
  5370.  
  5371.   sendMessage: function (aBody, aSubject) {
  5372.     // generate a mailto url based on the url and the url's title
  5373.     var mailtoUrl = "mailto:";
  5374.     if (aBody) {
  5375.       mailtoUrl += "?body=" + encodeURIComponent(aBody);
  5376.       mailtoUrl += "&subject=" + encodeURIComponent(aSubject);
  5377.     }
  5378.  
  5379.     var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  5380.                               .getService(Components.interfaces.nsIIOService);
  5381.     var uri = ioService.newURI(mailtoUrl, null, null);
  5382.  
  5383.     // now pass this uri to the operating system
  5384.     this._launchExternalUrl(uri);
  5385.   },
  5386.  
  5387.   // a generic method which can be used to pass arbitrary urls to the operating
  5388.   // system.
  5389.   // aURL --> a nsIURI which represents the url to launch
  5390.   _launchExternalUrl: function (aURL) {
  5391.     var extProtocolSvc =
  5392.        Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]
  5393.                  .getService(Components.interfaces.nsIExternalProtocolService);
  5394.     if (extProtocolSvc)
  5395.       extProtocolSvc.loadUrl(aURL);
  5396.   }
  5397. };
  5398.  
  5399. function BrowserOpenAddonsMgr(aPane)
  5400. {
  5401.   const EMTYPE = "Extension:Manager";
  5402.   var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  5403.                      .getService(Components.interfaces.nsIWindowMediator);
  5404.   var theEM = wm.getMostRecentWindow(EMTYPE);
  5405.   if (theEM) {
  5406.     theEM.focus();
  5407.     if (aPane)
  5408.       theEM.showView(aPane);
  5409.     return;
  5410.   }
  5411.  
  5412.   const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  5413.   const EMFEATURES = "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable";
  5414.   if (aPane)
  5415.     window.openDialog(EMURL, "", EMFEATURES, aPane);
  5416.   else
  5417.     window.openDialog(EMURL, "", EMFEATURES);
  5418. }
  5419.  
  5420. function escapeNameValuePair(aName, aValue, aIsFormUrlEncoded)
  5421. {
  5422.   if (aIsFormUrlEncoded)
  5423.     return escape(aName + "=" + aValue);
  5424.   else
  5425.     return escape(aName) + "=" + escape(aValue);
  5426. }
  5427.  
  5428. function AddKeywordForSearchField()
  5429. {
  5430.   var node = document.popupNode;
  5431.  
  5432.   var charset = node.ownerDocument.characterSet;
  5433.  
  5434.   var docURI = makeURI(node.ownerDocument.URL,
  5435.                        charset);
  5436.  
  5437.   var formURI = makeURI(node.form.getAttribute("action"),
  5438.                         charset,
  5439.                         docURI);
  5440.  
  5441.   var spec = formURI.spec;
  5442.  
  5443.   var isURLEncoded = 
  5444.                (node.form.method.toUpperCase() == "POST"
  5445.                 && (node.form.enctype == "application/x-www-form-urlencoded" ||
  5446.                     node.form.enctype == ""));
  5447.  
  5448.   var el, type;
  5449.   var formData = [];
  5450.  
  5451.   for (var i=0; i < node.form.elements.length; i++) {
  5452.     el = node.form.elements[i];
  5453.  
  5454.     if (!el.type) // happens with fieldsets
  5455.       continue;
  5456.  
  5457.     if (el == node) {
  5458.       formData.push((isURLEncoded) ? escapeNameValuePair(el.name, "%s", true) :
  5459.                                      // Don't escape "%s", just append
  5460.                                      escapeNameValuePair(el.name, "", false) + "%s");
  5461.       continue;
  5462.     }
  5463.  
  5464.     type = el.type.toLowerCase();
  5465.     
  5466.     if ((type == "text" || type == "hidden" || type == "textarea") ||
  5467.         ((type == "checkbox" || type == "radio") && el.checked)) {
  5468.       formData.push(escapeNameValuePair(el.name, el.value, isURLEncoded));
  5469.     } else if (el instanceof HTMLSelectElement && el.selectedIndex >= 0) {
  5470.       for (var j=0; j < el.options.length; j++) {
  5471.         if (el.options[j].selected)
  5472.           formData.push(escapeNameValuePair(el.name, el.options[j].value,
  5473.                                             isURLEncoded));
  5474.       }
  5475.     }
  5476.   }
  5477.  
  5478.   var postData;
  5479.  
  5480.   if (isURLEncoded)
  5481.     postData = formData.join("&");
  5482.   else
  5483.     spec += "?" + formData.join("&");
  5484.  
  5485.   var description = PlacesUIUtils.getDescriptionFromDocument(node.ownerDocument);
  5486.   PlacesUIUtils.showMinimalAddBookmarkUI(makeURI(spec), "", description, null,
  5487.                                          null, null, "", postData, charset);
  5488. }
  5489.  
  5490. function SwitchDocumentDirection(aWindow) {
  5491.   aWindow.document.dir = (aWindow.document.dir == "ltr" ? "rtl" : "ltr");
  5492.   for (var run = 0; run < aWindow.frames.length; run++)
  5493.     SwitchDocumentDirection(aWindow.frames[run]);
  5494. }
  5495.  
  5496. function getPluginInfo(pluginElement)
  5497. {
  5498.   var tagMimetype;
  5499.   var pluginsPage;
  5500.   if (pluginElement instanceof HTMLAppletElement) {
  5501.     tagMimetype = "application/x-java-vm";
  5502.   } else {
  5503.     if (pluginElement instanceof HTMLObjectElement) {
  5504.       pluginsPage = pluginElement.getAttribute("codebase");
  5505.     } else {
  5506.       pluginsPage = pluginElement.getAttribute("pluginspage");
  5507.     }
  5508.  
  5509.     // only attempt if a pluginsPage is defined.
  5510.     if (pluginsPage) {
  5511.       var doc = pluginElement.ownerDocument;
  5512.       var docShell = findChildShell(doc, gBrowser.selectedBrowser.docShell, null);
  5513.       try {
  5514.         pluginsPage = makeURI(pluginsPage, doc.characterSet, docShell.currentURI).spec;
  5515.       } catch (ex) { 
  5516.         pluginsPage = "";
  5517.       }
  5518.     }
  5519.  
  5520.     tagMimetype = pluginElement.QueryInterface(Components.interfaces.nsIObjectLoadingContent)
  5521.                                .actualType;
  5522.  
  5523.     if (tagMimetype == "") {
  5524.       tagMimetype = pluginElement.type;
  5525.     }
  5526.   }
  5527.  
  5528.   return {mimetype: tagMimetype, pluginsPage: pluginsPage};
  5529. }
  5530.  
  5531. function missingPluginInstaller(){
  5532. }
  5533.  
  5534. missingPluginInstaller.prototype.installSinglePlugin = function(aEvent){
  5535.   var missingPluginsArray = {};
  5536.  
  5537.   var pluginInfo = getPluginInfo(aEvent.target);
  5538.   missingPluginsArray[pluginInfo.mimetype] = pluginInfo;
  5539.  
  5540.   if (missingPluginsArray) {
  5541.     window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul",
  5542.                       "PFSWindow", "chrome,centerscreen,resizable=yes",
  5543.                       {plugins: missingPluginsArray, browser: gBrowser.selectedBrowser});
  5544.   }
  5545.  
  5546.   aEvent.stopPropagation();
  5547. }
  5548.  
  5549. missingPluginInstaller.prototype.managePlugins = function(aEvent){
  5550.   BrowserOpenAddonsMgr("plugins");
  5551.   aEvent.stopPropagation();
  5552. }
  5553.  
  5554. missingPluginInstaller.prototype.newMissingPlugin = function(aEvent){
  5555.   // Since we are expecting also untrusted events, make sure
  5556.   // that the target is a plugin
  5557.   if (!(aEvent.target instanceof Components.interfaces.nsIObjectLoadingContent))
  5558.     return;
  5559.  
  5560.   // For broken non-object plugin tags, register a click handler so
  5561.   // that the user can click the plugin replacement to get the new
  5562.   // plugin. Object tags can, and often do, deal with that themselves,
  5563.   // so don't stomp on the page developers toes.
  5564.  
  5565.   if (aEvent.type != "PluginBlocklisted" &&
  5566.       !(aEvent.target instanceof HTMLObjectElement)) {
  5567.     aEvent.target.addEventListener("click",
  5568.                                    gMissingPluginInstaller.installSinglePlugin,
  5569.                                    true);
  5570.   }
  5571.  
  5572.   try {
  5573.     if (gPrefService.getBoolPref("plugins.hide_infobar_for_missing_plugin"))
  5574.       return;
  5575.   } catch (ex) {} // if the pref is missing, treat it as false, which shows the infobar
  5576.  
  5577.   var browser = gBrowser.getBrowserForDocument(aEvent.target.ownerDocument
  5578.                                                      .defaultView.top.document);
  5579.   if (!browser.missingPlugins)
  5580.     browser.missingPlugins = {};
  5581.  
  5582.   var pluginInfo = getPluginInfo(aEvent.target);
  5583.  
  5584.   browser.missingPlugins[pluginInfo.mimetype] = pluginInfo;
  5585.  
  5586.   var notificationBox = gBrowser.getNotificationBox(browser);
  5587.  
  5588.   // If there is already a missing plugin notification then do nothing
  5589.   if (notificationBox.getNotificationWithValue("missing-plugins"))
  5590.     return;
  5591.   var blockedNotification = notificationBox.getNotificationWithValue("blocked-plugins");
  5592.   var priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  5593.  
  5594.   if (aEvent.type == "PluginBlocklisted") {
  5595.     if (blockedNotification)
  5596.       return;
  5597.  
  5598.     let iconURL = "chrome://mozapps/skin/plugins/pluginBlocked-16.png";
  5599.     let messageString = gNavigatorBundle.getString("blockedpluginsMessage.title");
  5600.     let buttons = [{
  5601.       label: gNavigatorBundle.getString("blockedpluginsMessage.infoButton.label"),
  5602.       accessKey: gNavigatorBundle.getString("blockedpluginsMessage.infoButton.accesskey"),
  5603.       popup: null,
  5604.       callback: blocklistInfo
  5605.     }, {
  5606.       label: gNavigatorBundle.getString("blockedpluginsMessage.searchButton.label"),
  5607.       accessKey: gNavigatorBundle.getString("blockedpluginsMessage.searchButton.accesskey"),
  5608.       popup: null,
  5609.       callback: pluginsMissing
  5610.     }];
  5611.  
  5612.     notificationBox.appendNotification(messageString, "blocked-plugins",
  5613.                                        iconURL, priority, buttons);
  5614.   }
  5615.   else if (aEvent.type == "PluginNotFound") {
  5616.     // Cancel any notification about blocklisting
  5617.     if (blockedNotification)
  5618.       blockedNotification.close();
  5619.  
  5620.     let iconURL = "chrome://mozapps/skin/plugins/pluginGeneric-16.png";
  5621.     let messageString = gNavigatorBundle.getString("missingpluginsMessage.title");
  5622.     let buttons = [{
  5623.       label: gNavigatorBundle.getString("missingpluginsMessage.button.label"),
  5624.       accessKey: gNavigatorBundle.getString("missingpluginsMessage.button.accesskey"),
  5625.       popup: null,
  5626.       callback: pluginsMissing
  5627.     }];
  5628.   
  5629.     notificationBox.appendNotification(messageString, "missing-plugins",
  5630.                                        iconURL, priority, buttons);
  5631.   }
  5632. }
  5633.  
  5634. missingPluginInstaller.prototype.newDisabledPlugin = function(aEvent){
  5635.   // Since we are expecting also untrusted events, make sure
  5636.   // that the target is a plugin
  5637.   if (!(aEvent.target instanceof Components.interfaces.nsIObjectLoadingContent))
  5638.     return;
  5639.  
  5640.   aEvent.target.addEventListener("click",
  5641.                                  gMissingPluginInstaller.managePlugins,
  5642.                                  true);
  5643. }
  5644.  
  5645. missingPluginInstaller.prototype.refreshBrowser = function(aEvent) {
  5646.   // browser elements are anonymous so we can't just use target.
  5647.   var browser = aEvent.originalTarget;
  5648.   var notificationBox = gBrowser.getNotificationBox(browser);
  5649.   var notification = notificationBox.getNotificationWithValue("missing-plugins");
  5650.  
  5651.   // clear the plugin list, now that at least one plugin has been installed
  5652.   browser.missingPlugins = null;
  5653.   if (notification) {
  5654.     // reset UI
  5655.     notificationBox.removeNotification(notification);
  5656.   }
  5657.   // reload the browser to make the new plugin show.
  5658.   browser.reload();
  5659. }
  5660.  
  5661. function blocklistInfo()
  5662. {
  5663.   var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  5664.                             .getService(Components.interfaces.nsIURLFormatter);
  5665.   var url = formatter.formatURLPref("extensions.blocklist.detailsURL");
  5666.   gBrowser.loadOneTab(url, null, null, null, false, false);
  5667.   return true;
  5668. }
  5669.  
  5670. function pluginsMissing()
  5671. {
  5672.   // get the urls of missing plugins
  5673.   var missingPluginsArray = gBrowser.selectedBrowser.missingPlugins;
  5674.   if (missingPluginsArray) {
  5675.     window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul",
  5676.                       "PFSWindow", "chrome,centerscreen,resizable=yes",
  5677.                       {plugins: missingPluginsArray, browser: gBrowser.selectedBrowser});
  5678.   }
  5679. }
  5680.  
  5681. var gMissingPluginInstaller = new missingPluginInstaller();
  5682.  
  5683. function convertFromUnicode(charset, str)
  5684. {
  5685.   try {
  5686.     var unicodeConverter = Components
  5687.        .classes["@mozilla.org/intl/scriptableunicodeconverter"]
  5688.        .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
  5689.     unicodeConverter.charset = charset;
  5690.     str = unicodeConverter.ConvertFromUnicode(str);
  5691.     return str + unicodeConverter.Finish();
  5692.   } catch(ex) {
  5693.     return null; 
  5694.   }
  5695. }
  5696.  
  5697. /**
  5698.  * The Feed Handler object manages discovery of RSS/ATOM feeds in web pages
  5699.  * and shows UI when they are discovered. 
  5700.  */
  5701. var FeedHandler = {
  5702.   /**
  5703.    * The click handler for the Feed icon in the location bar. Opens the
  5704.    * subscription page if user is not given a choice of feeds.
  5705.    * (Otherwise the list of available feeds will be presented to the 
  5706.    * user in a popup menu.)
  5707.    */
  5708.   onFeedButtonClick: function(event) {
  5709.     event.stopPropagation();
  5710.  
  5711.     if (event.target.hasAttribute("feed") &&
  5712.         event.eventPhase == Event.AT_TARGET &&
  5713.         (event.button == 0 || event.button == 1)) {
  5714.         this.subscribeToFeed(null, event);
  5715.     }
  5716.   },
  5717.   
  5718.   /**
  5719.    * Called when the user clicks on the Feed icon in the location bar. 
  5720.    * Builds a menu of unique feeds associated with the page, and if there
  5721.    * is only one, shows the feed inline in the browser window. 
  5722.    * @param   menuPopup
  5723.    *          The feed list menupopup to be populated.
  5724.    * @returns true if the menu should be shown, false if there was only
  5725.    *          one feed and the feed should be shown inline in the browser
  5726.    *          window (do not show the menupopup).
  5727.    */
  5728.   buildFeedList: function(menuPopup) {
  5729.     var feeds = gBrowser.selectedBrowser.feeds;
  5730.     if (feeds == null) {
  5731.       // XXX hack -- menu opening depends on setting of an "open"
  5732.       // attribute, and the menu refuses to open if that attribute is
  5733.       // set (because it thinks it's already open).  onpopupshowing gets
  5734.       // called after the attribute is unset, and it doesn't get unset
  5735.       // if we return false.  so we unset it here; otherwise, the menu
  5736.       // refuses to work past this point.
  5737.       menuPopup.parentNode.removeAttribute("open");
  5738.       return false;
  5739.     }
  5740.  
  5741.     while (menuPopup.firstChild)
  5742.       menuPopup.removeChild(menuPopup.firstChild);
  5743.  
  5744.     if (feeds.length == 1) {
  5745.       var feedButton = document.getElementById("feed-button");
  5746.       if (feedButton)
  5747.         feedButton.setAttribute("feed", feeds[0].href);
  5748.       return false;
  5749.     }
  5750.  
  5751.     // Build the menu showing the available feed choices for viewing. 
  5752.     for (var i = 0; i < feeds.length; ++i) {
  5753.       var feedInfo = feeds[i];
  5754.       var menuItem = document.createElement("menuitem");
  5755.       var baseTitle = feedInfo.title || feedInfo.href;
  5756.       var labelStr = gNavigatorBundle.getFormattedString("feedShowFeedNew", [baseTitle]);
  5757.       menuItem.setAttribute("label", labelStr);
  5758.       menuItem.setAttribute("feed", feedInfo.href);
  5759.       menuItem.setAttribute("tooltiptext", feedInfo.href);
  5760.       menuItem.setAttribute("crop", "center");
  5761.       menuPopup.appendChild(menuItem);
  5762.     }
  5763.     return true;
  5764.   },
  5765.   
  5766.   /**
  5767.    * Subscribe to a given feed.  Called when
  5768.    *   1. Page has a single feed and user clicks feed icon in location bar
  5769.    *   2. Page has a single feed and user selects Subscribe menu item
  5770.    *   3. Page has multiple feeds and user selects from feed icon popup
  5771.    *   4. Page has multiple feeds and user selects from Subscribe submenu
  5772.    * @param   href
  5773.    *          The feed to subscribe to. May be null, in which case the
  5774.    *          event target's feed attribute is examined.
  5775.    * @param   event
  5776.    *          The event this method is handling. Used to decide where 
  5777.    *          to open the preview UI. (Optional, unless href is null)
  5778.    */
  5779.   subscribeToFeed: function(href, event) {
  5780.     // Just load the feed in the content area to either subscribe or show the
  5781.     // preview UI
  5782.     if (!href)
  5783.       href = event.target.getAttribute("feed");
  5784.     urlSecurityCheck(href, gBrowser.contentPrincipal,
  5785.                      Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
  5786.     var feedURI = makeURI(href, document.characterSet);
  5787.     // Use the feed scheme so X-Moz-Is-Feed will be set
  5788.     // The value doesn't matter
  5789.     if (/^https?/.test(feedURI.scheme))
  5790.       href = "feed:" + href;
  5791.     this.loadFeed(href, event);
  5792.   },
  5793.  
  5794.   loadFeed: function(href, event) {
  5795.     var feeds = gBrowser.selectedBrowser.feeds;
  5796.     try {
  5797.       openUILink(href, event, false, true, false, null);
  5798.     }
  5799.     finally {
  5800.       // We might default to a livebookmarks modal dialog, 
  5801.       // so reset that if the user happens to click it again
  5802.       gBrowser.selectedBrowser.feeds = feeds;
  5803.     }
  5804.   },
  5805.  
  5806.   /**
  5807.    * Update the browser UI to show whether or not feeds are available when
  5808.    * a page is loaded or the user switches tabs to a page that has feeds. 
  5809.    */
  5810.   updateFeeds: function() {
  5811.     var feedButton = document.getElementById("feed-button");
  5812.     if (!this._feedMenuitem)
  5813.       this._feedMenuitem = document.getElementById("subscribeToPageMenuitem");
  5814.     if (!this._feedMenupopup)
  5815.       this._feedMenupopup = document.getElementById("subscribeToPageMenupopup");
  5816.  
  5817.     var feeds = gBrowser.mCurrentBrowser.feeds;
  5818.     if (!feeds || feeds.length == 0) {
  5819.       if (feedButton) {
  5820.         feedButton.removeAttribute("feeds");
  5821.         feedButton.removeAttribute("feed");
  5822.         feedButton.setAttribute("tooltiptext", 
  5823.                                 gNavigatorBundle.getString("feedNoFeeds"));
  5824.       }
  5825.       this._feedMenuitem.setAttribute("disabled", "true");
  5826.       this._feedMenupopup.setAttribute("hidden", "true");
  5827.       this._feedMenuitem.removeAttribute("hidden");
  5828.     } else {
  5829.       if (feedButton) {
  5830.         feedButton.setAttribute("feeds", "true");
  5831.         feedButton.setAttribute("tooltiptext", 
  5832.                                 gNavigatorBundle.getString("feedHasFeedsNew"));
  5833.       }
  5834.       
  5835.       if (feeds.length > 1) {
  5836.         this._feedMenuitem.setAttribute("hidden", "true");
  5837.         this._feedMenupopup.removeAttribute("hidden");
  5838.         if (feedButton)
  5839.           feedButton.removeAttribute("feed");
  5840.       } else {
  5841.         if (feedButton)
  5842.           feedButton.setAttribute("feed", feeds[0].href);
  5843.  
  5844.         this._feedMenuitem.setAttribute("feed", feeds[0].href);
  5845.         this._feedMenuitem.removeAttribute("disabled");
  5846.         this._feedMenuitem.removeAttribute("hidden");
  5847.         this._feedMenupopup.setAttribute("hidden", "true");
  5848.       }
  5849.     }
  5850.   }, 
  5851.  
  5852.   addFeed: function(link, targetDoc) {
  5853.     // find which tab this is for, and set the attribute on the browser
  5854.     var browserForLink = gBrowser.getBrowserForDocument(targetDoc);
  5855.     if (!browserForLink) {
  5856.       // ignore feeds loaded in subframes (see bug 305472)
  5857.       return;
  5858.     }
  5859.  
  5860.     if (!browserForLink.feeds)
  5861.       browserForLink.feeds = [];
  5862.  
  5863.     browserForLink.feeds.push({ href: link.href, title: link.title });
  5864.  
  5865.     if (browserForLink == gBrowser.mCurrentBrowser) {
  5866.       var feedButton = document.getElementById("feed-button");
  5867.       if (feedButton) {
  5868.         feedButton.setAttribute("feeds", "true");
  5869.         feedButton.setAttribute("tooltiptext", 
  5870.                                 gNavigatorBundle.getString("feedHasFeedsNew"));
  5871.       }
  5872.     }
  5873.   }
  5874. };
  5875.  
  5876. //@line 40 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-places.js"
  5877.  
  5878.  
  5879. var StarUI = {
  5880.   _itemId: -1,
  5881.   uri: null,
  5882.   _batching: false,
  5883.  
  5884.   // nsISupports
  5885.   QueryInterface: function SU_QueryInterface(aIID) {
  5886.     if (aIID.equals(Ci.nsIDOMEventListener) ||
  5887.         aIID.equals(Ci.nsISupports))
  5888.       return this;
  5889.  
  5890.     throw Cr.NS_NOINTERFACE;
  5891.   },
  5892.  
  5893.   _element: function(aID) {
  5894.     return document.getElementById(aID);
  5895.   },
  5896.  
  5897.   // Edit-bookmark panel
  5898.   get panel() {
  5899.     delete this.panel;
  5900.     var element = this._element("editBookmarkPanel");
  5901.     // initially the panel is hidden
  5902.     // to avoid impacting startup / new window performance
  5903.     element.hidden = false;
  5904.     element.addEventListener("popuphidden", this, false);
  5905.     element.addEventListener("keypress", this, true);
  5906.     return this.panel = element;
  5907.   },
  5908.  
  5909.   // list of command elements (by id) to disable when the panel is opened
  5910.   _blockedCommands: ["cmd_close", "cmd_closeWindow"],
  5911.   _blockCommands: function SU__blockCommands() {
  5912.     for each(var key in this._blockedCommands) {
  5913.       var elt = this._element(key);
  5914.       // make sure not to permanently disable this item (see bug 409155)
  5915.       if (elt.hasAttribute("wasDisabled"))
  5916.         continue;
  5917.       if (elt.getAttribute("disabled") == "true")
  5918.         elt.setAttribute("wasDisabled", "true");
  5919.       else {
  5920.         elt.setAttribute("wasDisabled", "false");
  5921.         elt.setAttribute("disabled", "true");
  5922.       }
  5923.     }
  5924.   },
  5925.  
  5926.   _restoreCommandsState: function SU__restoreCommandsState() {
  5927.     for each(var key in this._blockedCommands) {
  5928.       var elt = this._element(key);
  5929.       if (elt.getAttribute("wasDisabled") != "true")
  5930.         elt.removeAttribute("disabled");
  5931.       elt.removeAttribute("wasDisabled");
  5932.     }
  5933.   },
  5934.  
  5935.   // nsIDOMEventListener
  5936.   handleEvent: function SU_handleEvent(aEvent) {
  5937.     switch (aEvent.type) {
  5938.       case "popuphidden":
  5939.         if (aEvent.originalTarget == this.panel) {
  5940.           if (!this._element("editBookmarkPanelContent").hidden)
  5941.             this.quitEditMode();
  5942.           this._restoreCommandsState();
  5943.           this._itemId = -1;
  5944.           this._uri = null;
  5945.           if (this._batching) {
  5946.             PlacesUIUtils.ptm.endBatch();
  5947.             this._batching = false;
  5948.           }
  5949.         }
  5950.         break;
  5951.       case "keypress":
  5952.         if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) {
  5953.           // If the panel is visible the ESC key is mapped to the cancel button
  5954.           // unless we are editing a folder in the folderTree, or an
  5955.           // autocomplete popup is open.
  5956.           if (!this._element("editBookmarkPanelContent").hidden) {
  5957.             var elt = aEvent.target;
  5958.             if ((elt.localName != "tree" || !elt.hasAttribute("editing")) &&
  5959.                 !elt.popupOpen)
  5960.               this.cancelButtonOnCommand();
  5961.           }
  5962.         }
  5963.         else if (aEvent.keyCode == KeyEvent.DOM_VK_RETURN) {
  5964.           // hide the panel unless the folder tree or an expander are focused
  5965.           // or an autocomplete popup is open.
  5966.           if (aEvent.target.localName != "tree" &&
  5967.               aEvent.target.className != "expander-up" &&
  5968.               aEvent.target.className != "expander-down" &&
  5969.               !aEvent.target.popupOpen)
  5970.             this.panel.hidePopup();
  5971.         }
  5972.         break;
  5973.     }
  5974.   },
  5975.  
  5976.   _overlayLoaded: false,
  5977.   _overlayLoading: false,
  5978.   showEditBookmarkPopup:
  5979.   function SU_showEditBookmarkPopup(aItemId, aAnchorElement, aPosition) {
  5980.     // Performance: load the overlay the first time the panel is opened
  5981.     // (see bug 392443).
  5982.     if (this._overlayLoading)
  5983.       return;
  5984.  
  5985.     if (this._overlayLoaded) {
  5986.       this._doShowEditBookmarkPanel(aItemId, aAnchorElement, aPosition);
  5987.       return;
  5988.     }
  5989.  
  5990.     var loadObserver = {
  5991.       _self: this,
  5992.       _itemId: aItemId,
  5993.       _anchorElement: aAnchorElement,
  5994.       _position: aPosition,
  5995.       observe: function (aSubject, aTopic, aData) {
  5996.         this._self._overlayLoading = false;
  5997.         this._self._overlayLoaded = true;
  5998.         this._self._doShowEditBookmarkPanel(this._itemId, this._anchorElement,
  5999.                                             this._position);
  6000.       }
  6001.     };
  6002.     this._overlayLoading = true;
  6003.     document.loadOverlay("chrome://browser/content/places/editBookmarkOverlay.xul",
  6004.                          loadObserver);
  6005.   },
  6006.  
  6007.   _doShowEditBookmarkPanel:
  6008.   function SU__doShowEditBookmarkPanel(aItemId, aAnchorElement, aPosition) {
  6009.     if (this.panel.state != "closed")
  6010.       return;
  6011.  
  6012.     this._blockCommands(); // un-done in the popuphiding handler
  6013.  
  6014.     // Move the header (star, title, possibly a button) into the grid,
  6015.     // so that it aligns nicely with the other items (bug 484022).
  6016.     var rows = this._element("editBookmarkPanelGrid").lastChild;
  6017.     var header = this._element("editBookmarkPanelHeader");
  6018.     rows.insertBefore(header, rows.firstChild);
  6019.     header.hidden = false;
  6020.  
  6021.     var bundle = this._element("bundle_browser");
  6022.  
  6023.     // Set panel title:
  6024.     // if we are batching, i.e. the bookmark has been added now,
  6025.     // then show Page Bookmarked, else if the bookmark did already exist,
  6026.     // we are about editing it, then use Edit This Bookmark.
  6027.     this._element("editBookmarkPanelTitle").value =
  6028.       this._batching ?
  6029.         bundle.getString("editBookmarkPanel.pageBookmarkedTitle") :
  6030.         bundle.getString("editBookmarkPanel.editBookmarkTitle");
  6031.  
  6032.     // No description; show the Done, Cancel;
  6033.     // hide the Edit, Undo buttons
  6034.     this._element("editBookmarkPanelDescription").textContent = "";
  6035.     this._element("editBookmarkPanelBottomButtons").hidden = false;
  6036.     this._element("editBookmarkPanelContent").hidden = false;
  6037.     this._element("editBookmarkPanelEditButton").hidden = true;
  6038.     this._element("editBookmarkPanelUndoRemoveButton").hidden = true;
  6039.  
  6040.     // The remove button is shown only if we're not already batching, i.e.
  6041.     // if the cancel button/ESC does not remove the bookmark.
  6042.     this._element("editBookmarkPanelRemoveButton").hidden = this._batching;
  6043.  
  6044.     // The label of the remove button differs if the URI is bookmarked
  6045.     // multiple times.
  6046.     var bookmarks = PlacesUtils.getBookmarksForURI(gBrowser.currentURI);
  6047.     var forms = bundle.getString("editBookmark.removeBookmarks.label");
  6048.     var label = PluralForm.get(bookmarks.length, forms).replace("#1", bookmarks.length);
  6049.     this._element("editBookmarkPanelRemoveButton").label = label;
  6050.  
  6051.     // unset the unstarred state, if set
  6052.     this._element("editBookmarkPanelStarIcon").removeAttribute("unstarred");
  6053.  
  6054.     this._itemId = aItemId !== undefined ? aItemId : this._itemId;
  6055.     this.beginBatch();
  6056.  
  6057.     // Consume dismiss clicks, see bug 400924
  6058.     this.panel.popupBoxObject
  6059.         .setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  6060.     this.panel.openPopup(aAnchorElement, aPosition, -1, -1);
  6061.  
  6062.     gEditItemOverlay.initPanel(this._itemId,
  6063.                                { hiddenRows: ["description", "location",
  6064.                                               "loadInSidebar", "keyword"] });
  6065.   },
  6066.  
  6067.   panelShown:
  6068.   function SU_panelShown(aEvent) {
  6069.     if (aEvent.target == this.panel) {
  6070.       if (!this._element("editBookmarkPanelContent").hidden) {
  6071.         var namePicker = this._element("editBMPanel_namePicker");
  6072.         namePicker.focus();
  6073.         namePicker.select();
  6074.       }
  6075.       else
  6076.         this.panel.focus();
  6077.     }
  6078.   },
  6079.  
  6080.   showPageBookmarkedNotification:
  6081.   function PCH_showPageBookmarkedNotification(aItemId, aAnchorElement, aPosition) {
  6082.     this._blockCommands(); // un-done in the popuphiding handler
  6083.  
  6084.     var bundle = this._element("bundle_browser");
  6085.     var brandBundle = this._element("bundle_brand");
  6086.     var brandShortName = brandBundle.getString("brandShortName");
  6087.  
  6088.     // "Page Bookmarked" title
  6089.     this._element("editBookmarkPanelTitle").value =
  6090.       bundle.getString("editBookmarkPanel.pageBookmarkedTitle");
  6091.  
  6092.     // description
  6093.     this._element("editBookmarkPanelDescription").textContent =
  6094.       bundle.getFormattedString("editBookmarkPanel.pageBookmarkedDescription",
  6095.                                 [brandShortName]);
  6096.  
  6097.     // show the "Edit.." button and the Remove Bookmark button, hide the
  6098.     // undo-remove-bookmark button.
  6099.     this._element("editBookmarkPanelEditButton").hidden = false;
  6100.     this._element("editBookmarkPanelRemoveButton").hidden = false;
  6101.     this._element("editBookmarkPanelUndoRemoveButton").hidden = true;
  6102.  
  6103.     // unset the unstarred state, if set
  6104.     this._element("editBookmarkPanelStarIcon").removeAttribute("unstarred");
  6105.  
  6106.     this._itemId = aItemId !== undefined ? aItemId : this._itemId;
  6107.     if (this.panel.state == "closed") {
  6108.       // Consume dismiss clicks, see bug 400924
  6109.       this.panel.popupBoxObject
  6110.           .setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  6111.       this.panel.openPopup(aAnchorElement, aPosition, -1, -1);
  6112.     }
  6113.     else
  6114.       this.panel.focus();
  6115.   },
  6116.  
  6117.   quitEditMode: function SU_quitEditMode() {
  6118.     this._element("editBookmarkPanelContent").hidden = true;
  6119.     this._element("editBookmarkPanelBottomButtons").hidden = true;
  6120.     gEditItemOverlay.uninitPanel(true);
  6121.   },
  6122.  
  6123.   editButtonCommand: function SU_editButtonCommand() {
  6124.     this.showEditBookmarkPopup();
  6125.   },
  6126.  
  6127.   cancelButtonOnCommand: function SU_cancelButtonOnCommand() {
  6128.     // The order here is important! We have to hide the panel first, otherwise
  6129.     // changes done as part of Undo may change the panel contents and by
  6130.     // that force it to commit more transactions
  6131.     this.panel.hidePopup();
  6132.     this.endBatch();
  6133.     PlacesUIUtils.ptm.undoTransaction();
  6134.   },
  6135.  
  6136.   removeBookmarkButtonCommand: function SU_removeBookmarkButtonCommand() {
  6137. //@line 326 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-places.js"
  6138.  
  6139.     // cache its uri so we can get the new itemId in the case of undo
  6140.     this._uri = PlacesUtils.bookmarks.getBookmarkURI(this._itemId);
  6141.  
  6142.     // remove all bookmarks for the bookmark's url, this also removes
  6143.     // the tags for the url
  6144.     var itemIds = PlacesUtils.getBookmarksForURI(this._uri);
  6145.     for (var i=0; i < itemIds.length; i++) {
  6146.       var txn = PlacesUIUtils.ptm.removeItem(itemIds[i]);
  6147.       PlacesUIUtils.ptm.doTransaction(txn);
  6148.     }
  6149.  
  6150. //@line 343 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-places.js"
  6151.       this.panel.hidePopup();
  6152.   },
  6153.  
  6154.   undoRemoveBookmarkCommand: function SU_undoRemoveBookmarkCommand() {
  6155.     // restore the bookmark by undoing the last transaction and go back
  6156.     // to the edit state
  6157.     this.endBatch();
  6158.     PlacesUIUtils.ptm.undoTransaction();
  6159.     this._itemId = PlacesUtils.getMostRecentBookmarkForURI(this._uri);
  6160.     this.showEditBookmarkPopup();
  6161.   },
  6162.  
  6163.   beginBatch: function SU_beginBatch() {
  6164.     if (!this._batching) {
  6165.       PlacesUIUtils.ptm.beginBatch();
  6166.       this._batching = true;
  6167.     }
  6168.   },
  6169.  
  6170.   endBatch: function SU_endBatch() {
  6171.     if (this._batching) {
  6172.       PlacesUIUtils.ptm.endBatch();
  6173.       this._batching = false;
  6174.     }
  6175.   }
  6176. }
  6177.  
  6178. var PlacesCommandHook = {
  6179.   /**
  6180.    * Adds a bookmark to the page loaded in the given browser.
  6181.    *
  6182.    * @param aBrowser
  6183.    *        a <browser> element.
  6184.    * @param [optional] aParent
  6185.    *        The folder in which to create a new bookmark if the page loaded in
  6186.    *        aBrowser isn't bookmarked yet, defaults to the unfiled root.
  6187.    * @param [optional] aShowEditUI
  6188.    *        whether or not to show the edit-bookmark UI for the bookmark item
  6189.    */  
  6190.   bookmarkPage: function PCH_bookmarkPage(aBrowser, aParent, aShowEditUI) {
  6191.     var uri = aBrowser.currentURI;
  6192.     var itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
  6193.     if (itemId == -1) {
  6194.       // Copied over from addBookmarkForBrowser:
  6195.       // Bug 52536: We obtain the URL and title from the nsIWebNavigation
  6196.       // associated with a <browser/> rather than from a DOMWindow.
  6197.       // This is because when a full page plugin is loaded, there is
  6198.       // no DOMWindow (?) but information about the loaded document
  6199.       // may still be obtained from the webNavigation.
  6200.       var webNav = aBrowser.webNavigation;
  6201.       var url = webNav.currentURI;
  6202.       var title;
  6203.       var description;
  6204.       var charset;
  6205.       try {
  6206.         title = webNav.document.title || url.spec;
  6207.         description = PlacesUIUtils.getDescriptionFromDocument(webNav.document);
  6208.         charset = webNav.document.characterSet;
  6209.       }
  6210.       catch (e) { }
  6211.  
  6212.       if (aShowEditUI) {
  6213.         // If we bookmark the page here (i.e. page was not "starred" already)
  6214.         // but open right into the "edit" state, start batching here, so
  6215.         // "Cancel" in that state removes the bookmark.
  6216.         StarUI.beginBatch();
  6217.       }
  6218.  
  6219.       var parent = aParent != undefined ?
  6220.                    aParent : PlacesUtils.unfiledBookmarksFolderId;
  6221.       var descAnno = { name: DESCRIPTION_ANNO, value: description };
  6222.       var txn = PlacesUIUtils.ptm.createItem(uri, parent, -1,
  6223.                                              title, null, [descAnno]);
  6224.       PlacesUIUtils.ptm.doTransaction(txn);
  6225.       // Set the character-set
  6226.       if (charset)
  6227.         PlacesUtils.history.setCharsetForURI(uri, charset);
  6228.       itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
  6229.     }
  6230.  
  6231.     // Revert the contents of the location bar
  6232.     if (gURLBar)
  6233.       gURLBar.handleRevert();
  6234.  
  6235.     // dock the panel to the star icon when possible, otherwise dock
  6236.     // it to the content area
  6237.     if (aBrowser.contentWindow == window.content) {
  6238.       var starIcon = aBrowser.ownerDocument.getElementById("star-button");
  6239.       if (starIcon && isElementVisible(starIcon)) {
  6240.         // Make sure the bookmark properties dialog hangs toward the middle of
  6241.         // the location bar in RTL builds
  6242.         var position = "after_end";
  6243.         if (gURLBar.getAttribute("chromedir") == "rtl")
  6244.           position = "after_start";
  6245.         if (aShowEditUI)
  6246.           StarUI.showEditBookmarkPopup(itemId, starIcon, position);
  6247. //@line 443 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-places.js"
  6248.         return;
  6249.       }
  6250.     }
  6251.  
  6252.     StarUI.showEditBookmarkPopup(itemId, aBrowser, "overlap");
  6253.   },
  6254.  
  6255.   /**
  6256.    * Adds a bookmark to the page loaded in the current tab. 
  6257.    */
  6258.   bookmarkCurrentPage: function PCH_bookmarkCurrentPage(aShowEditUI, aParent) {
  6259.     this.bookmarkPage(getBrowser().selectedBrowser, aParent, aShowEditUI);
  6260.   },
  6261.  
  6262.   /**
  6263.    * Adds a bookmark to the page targeted by a link.
  6264.    * @param aParent
  6265.    *        The folder in which to create a new bookmark if aURL isn't
  6266.    *        bookmarked.
  6267.    * @param aURL (string)
  6268.    *        the address of the link target
  6269.    * @param aTitle
  6270.    *        The link text
  6271.    */
  6272.   bookmarkLink: function PCH_bookmarkLink(aParent, aURL, aTitle) {
  6273.     var linkURI = makeURI(aURL);
  6274.     var itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
  6275.     if (itemId == -1)
  6276.       PlacesUIUtils.showMinimalAddBookmarkUI(linkURI, aTitle);
  6277.     else {
  6278.       PlacesUIUtils.showItemProperties(itemId,
  6279.                                        PlacesUtils.bookmarks.TYPE_BOOKMARK);
  6280.     }
  6281.   },
  6282.  
  6283.   /**
  6284.    * This function returns a list of nsIURI objects characterizing the
  6285.    * tabs currently open in the browser.  The URIs will appear in the
  6286.    * list in the order in which their corresponding tabs appeared.  However,
  6287.    * only the first instance of each URI will be returned.
  6288.    *
  6289.    * @returns a list of nsIURI objects representing unique locations open
  6290.    */
  6291.   _getUniqueTabInfo: function BATC__getUniqueTabInfo() {
  6292.     var tabList = [];
  6293.     var seenURIs = [];
  6294.  
  6295.     var browsers = getBrowser().browsers;
  6296.     for (var i = 0; i < browsers.length; ++i) {
  6297.       var webNav = browsers[i].webNavigation;
  6298.       var uri = webNav.currentURI;
  6299.  
  6300.       // skip redundant entries
  6301.       if (uri.spec in seenURIs)
  6302.         continue;
  6303.  
  6304.       // add to the set of seen URIs
  6305.       seenURIs[uri.spec] = true;
  6306.       tabList.push(uri);
  6307.     }
  6308.     return tabList;
  6309.   },
  6310.  
  6311.   /**
  6312.    * Adds a folder with bookmarks to all of the currently open tabs in this 
  6313.    * window.
  6314.    */
  6315.   bookmarkCurrentPages: function PCH_bookmarkCurrentPages() {
  6316.     var tabURIs = this._getUniqueTabInfo();
  6317.     PlacesUIUtils.showMinimalAddMultiBookmarkUI(tabURIs);
  6318.   },
  6319.  
  6320.   
  6321.   /**
  6322.    * Adds a Live Bookmark to a feed associated with the current page. 
  6323.    * @param     url
  6324.    *            The nsIURI of the page the feed was attached to
  6325.    * @title     title
  6326.    *            The title of the feed. Optional.
  6327.    * @subtitle  subtitle
  6328.    *            A short description of the feed. Optional.
  6329.    */
  6330.   addLiveBookmark: function PCH_addLiveBookmark(url, feedTitle, feedSubtitle) {
  6331.     var ios = 
  6332.         Cc["@mozilla.org/network/io-service;1"].
  6333.         getService(Ci.nsIIOService);
  6334.     var feedURI = ios.newURI(url, null, null);
  6335.     
  6336.     var doc = gBrowser.contentDocument;
  6337.     var title = (arguments.length > 1) ? feedTitle : doc.title;
  6338.  
  6339.     var description;
  6340.     if (arguments.length > 2)
  6341.       description = feedSubtitle;
  6342.     else
  6343.       description = PlacesUIUtils.getDescriptionFromDocument(doc);
  6344.  
  6345.     var toolbarIP =
  6346.       new InsertionPoint(PlacesUtils.bookmarks.toolbarFolder, -1);
  6347.     PlacesUIUtils.showMinimalAddLivemarkUI(feedURI, gBrowser.currentURI,
  6348.                                            title, description, toolbarIP, true);
  6349.   },
  6350.  
  6351.   /**
  6352.    * Opens the Places Organizer. 
  6353.    * @param   aLeftPaneRoot
  6354.    *          The query to select in the organizer window - options
  6355.    *          are: History, AllBookmarks, BookmarksMenu, BookmarksToolbar,
  6356.    *          UnfiledBookmarks and Tags.
  6357.    */
  6358.   showPlacesOrganizer: function PCH_showPlacesOrganizer(aLeftPaneRoot) {
  6359.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  6360.              getService(Ci.nsIWindowMediator);
  6361.     var organizer = wm.getMostRecentWindow("Places:Organizer");
  6362.     if (!organizer) {
  6363.       // No currently open places window, so open one with the specified mode.
  6364.       openDialog("chrome://browser/content/places/places.xul", 
  6365.                  "", "chrome,toolbar=yes,dialog=no,resizable", aLeftPaneRoot);
  6366.     }
  6367.     else {
  6368.       organizer.PlacesOrganizer.selectLeftPaneQuery(aLeftPaneRoot);
  6369.       organizer.focus();
  6370.     }
  6371.   },
  6372.  
  6373.   deleteButtonOnCommand: function PCH_deleteButtonCommand() {
  6374.     PlacesUtils.bookmarks.removeItem(gEditItemOverlay.itemId);
  6375.  
  6376.     // remove all tags for the associated url
  6377.     PlacesUtils.tagging.untagURI(gEditItemOverlay._uri, null);
  6378.  
  6379.     this.panel.hidePopup();
  6380.   }
  6381. };
  6382.  
  6383. // Functions for the history menu.
  6384. var HistoryMenu = {
  6385.   get _ss() {
  6386.     delete this._ss;
  6387.     return this._ss = Components.classes["@mozilla.org/browser/sessionstore;1"].
  6388.                       getService(Components.interfaces.nsISessionStore);
  6389.   },
  6390.  
  6391.   /**
  6392.    * popupshowing handler for the history menu.
  6393.    * @param aMenuPopup
  6394.    *        XULNode for the history menupopup
  6395.    */
  6396.   onPopupShowing: function PHM_onPopupShowing(aMenuPopup) {
  6397.     var resultNode = aMenuPopup.getResultNode();
  6398.     var wasOpen = resultNode.containerOpen;
  6399.     resultNode.containerOpen = true;
  6400.     document.getElementById("endHistorySeparator").hidden =
  6401.       resultNode.childCount == 0;
  6402.  
  6403.     if (!wasOpen)
  6404.       resultNode.containerOpen = false;
  6405.  
  6406.     // HistoryMenu.toggleRecentlyClosedTabs, HistoryMenu.toggleRecentlyClosedWindows
  6407.     // are defined in browser.js
  6408.     this.toggleRecentlyClosedTabs();
  6409.     this.toggleRecentlyClosedWindows();
  6410.   }
  6411. };
  6412.  
  6413. /**
  6414.  * Functions for handling events in the Bookmarks Toolbar and menu.
  6415.  */
  6416. var BookmarksEventHandler = {  
  6417.   /**
  6418.    * Handler for click event for an item in the bookmarks toolbar or menu.
  6419.    * Menus and submenus from the folder buttons bubble up to this handler.
  6420.    * Left-click is handled in the onCommand function.
  6421.    * When items are middle-clicked (or clicked with modifier), open in tabs.
  6422.    * If the click came through a menu, close the menu.
  6423.    * @param aEvent
  6424.    *        DOMEvent for the click
  6425.    */
  6426.   onClick: function BT_onClick(aEvent) {
  6427.     // Only handle middle-click or left-click with modifiers.
  6428. //@line 626 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-places.js"
  6429.     var modifKey = aEvent.ctrlKey || aEvent.shiftKey;
  6430. //@line 628 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-places.js"
  6431.     if (aEvent.button == 2 || (aEvent.button == 0 && !modifKey))
  6432.       return;
  6433.  
  6434.     var target = aEvent.originalTarget;
  6435.     // If this event bubbled up from a menu or menuitem, close the menus.
  6436.     // Do this before opening tabs, to avoid hiding the open tabs confirm-dialog.
  6437.     if (target.localName == "menu" || target.localName == "menuitem") {
  6438.       for (node = target.parentNode; node; node = node.parentNode) {
  6439.         if (node.localName == "menupopup")
  6440.           node.hidePopup();
  6441.         else if (node.localName != "menu")
  6442.           break;
  6443.       }
  6444.     }
  6445.  
  6446.     if (target.node && PlacesUtils.nodeIsContainer(target.node)) {
  6447.       // Don't open the root folder in tabs when the empty area on the toolbar
  6448.       // is middle-clicked or when a non-bookmark item except for Open in Tabs)
  6449.       // in a bookmarks menupopup is middle-clicked.
  6450.       if (target.localName == "menu" || target.localName == "toolbarbutton")
  6451.         PlacesUIUtils.openContainerNodeInTabs(target.node, aEvent);
  6452.     }
  6453.     else if (aEvent.button == 1) {
  6454.       // left-clicks with modifier are already served by onCommand
  6455.       this.onCommand(aEvent);
  6456.     }
  6457.   },
  6458.  
  6459.   /**
  6460.    * Handler for command event for an item in the bookmarks toolbar.
  6461.    * Menus and submenus from the folder buttons bubble up to this handler.
  6462.    * Opens the item.
  6463.    * @param aEvent 
  6464.    *        DOMEvent for the command
  6465.    */
  6466.   onCommand: function BM_onCommand(aEvent) {
  6467.     var target = aEvent.originalTarget;
  6468.     if (target.node)
  6469.       PlacesUIUtils.openNodeWithEvent(target.node, aEvent);
  6470.   },
  6471.  
  6472.   /**
  6473.    * Handler for popupshowing event for an item in bookmarks toolbar or menu.
  6474.    * If the item isn't the main bookmarks menu, add an "Open All in Tabs"
  6475.    * menuitem to the bottom of the popup.
  6476.    * @param event 
  6477.    *        DOMEvent for popupshowing
  6478.    */
  6479.   onPopupShowing: function BM_onPopupShowing(event) {
  6480.     var target = event.originalTarget;
  6481.     if (!target.hasAttribute("placespopup"))
  6482.       return;
  6483.  
  6484.     // Check if the popup contains at least 2 menuitems with places nodes
  6485.     var numNodes = 0;
  6486.     var hasMultipleURIs = false;
  6487.     var currentChild = target.firstChild;
  6488.     while (currentChild) {
  6489.       if (currentChild.localName == "menuitem" && currentChild.node) {
  6490.         if (++numNodes == 2) {
  6491.           hasMultipleURIs = true;
  6492.           break;
  6493.         }
  6494.       }
  6495.       currentChild = currentChild.nextSibling;
  6496.     }
  6497.  
  6498.     var itemId = target._resultNode.itemId;
  6499.     var siteURIString = "";
  6500.     if (itemId != -1 && PlacesUtils.livemarks.isLivemark(itemId)) {
  6501.       var siteURI = PlacesUtils.livemarks.getSiteURI(itemId);
  6502.       if (siteURI)
  6503.         siteURIString = siteURI.spec;
  6504.     }
  6505.  
  6506.     if (!siteURIString && target._endOptOpenSiteURI) {
  6507.         target.removeChild(target._endOptOpenSiteURI);
  6508.         target._endOptOpenSiteURI = null;
  6509.     }
  6510.  
  6511.     if (!hasMultipleURIs && target._endOptOpenAllInTabs) {
  6512.       target.removeChild(target._endOptOpenAllInTabs);
  6513.       target._endOptOpenAllInTabs = null;
  6514.     }
  6515.  
  6516.     if (!(hasMultipleURIs || siteURIString)) {
  6517.       // we don't have to show any option
  6518.       if (target._endOptSeparator) {
  6519.         target.removeChild(target._endOptSeparator);
  6520.         target._endOptSeparator = null;
  6521.         target._endMarker = -1;
  6522.       }
  6523.       return;
  6524.     }
  6525.  
  6526.     if (!target._endOptSeparator) {
  6527.       // create a separator before options
  6528.       target._endOptSeparator = document.createElement("menuseparator");
  6529.       target._endMarker = target.childNodes.length;
  6530.       target.appendChild(target._endOptSeparator);
  6531.     }
  6532.  
  6533.     if (siteURIString && !target._endOptOpenSiteURI) {
  6534.       // Add "Open (Feed Name)" menuitem if it's a livemark with a siteURI
  6535.       target._endOptOpenSiteURI = document.createElement("menuitem");
  6536.       target._endOptOpenSiteURI.setAttribute("siteURI", siteURIString);
  6537.       target._endOptOpenSiteURI.setAttribute("oncommand",
  6538.           "openUILink(this.getAttribute('siteURI'), event);");
  6539.       // If a user middle-clicks this item we serve the oncommand event
  6540.       // We are using checkForMiddleClick because of Bug 246720
  6541.       // Note: stopPropagation is needed to avoid serving middle-click 
  6542.       // with BT_onClick that would open all items in tabs
  6543.       target._endOptOpenSiteURI.setAttribute("onclick",
  6544.           "checkForMiddleClick(this, event); event.stopPropagation();");
  6545.       target._endOptOpenSiteURI.setAttribute("label",
  6546.           PlacesUIUtils.getFormattedString("menuOpenLivemarkOrigin.label",
  6547.           [target.parentNode.getAttribute("label")]));
  6548.       target.appendChild(target._endOptOpenSiteURI);
  6549.     }
  6550.  
  6551.     if (hasMultipleURIs && !target._endOptOpenAllInTabs) {
  6552.         // Add the "Open All in Tabs" menuitem if there are
  6553.         // at least two menuitems with places result nodes.
  6554.         target._endOptOpenAllInTabs = document.createElement("menuitem");
  6555.         target._endOptOpenAllInTabs.setAttribute("oncommand",
  6556.             "PlacesUIUtils.openContainerNodeInTabs(this.parentNode._resultNode, event);");
  6557.         target._endOptOpenAllInTabs.setAttribute("onclick",
  6558.             "checkForMiddleClick(this, event); event.stopPropagation();");
  6559.         target._endOptOpenAllInTabs.setAttribute("label",
  6560.             gNavigatorBundle.getString("menuOpenAllInTabs.label"));
  6561.         target.appendChild(target._endOptOpenAllInTabs);
  6562.     }
  6563.   },
  6564.  
  6565.   fillInBTTooltip: function(aTipElement) {
  6566.     if (!aTipElement.node)
  6567.       return false;
  6568.  
  6569.     //Show tooltips only for URL items
  6570.     if (!PlacesUtils.nodeIsURI(aTipElement.node))
  6571.       return false;
  6572.  
  6573.     var title = aTipElement.node.title;
  6574.     var url = aTipElement.node.uri;
  6575.  
  6576.     var tooltipTitle = document.getElementById("btTitleText");
  6577.     tooltipTitle.hidden = !title || (title == url);
  6578.     if (!tooltipTitle.hidden)
  6579.       tooltipTitle.textContent = title;
  6580.  
  6581.     var tooltipUrl = document.getElementById("btUrlText");
  6582.     tooltipUrl.value = url;
  6583.  
  6584.     //Show tooltip
  6585.     return true;
  6586.   }
  6587. };
  6588.  
  6589. /**
  6590.  * Drag and Drop handling specifically for the Bookmarks Menu item in the
  6591.  * top level menu bar
  6592.  */
  6593. var BookmarksMenuDropHandler = {
  6594.   /**
  6595.    * Need to tell the session to update the state of the cursor as we drag
  6596.    * over the Bookmarks Menu to show the "can drop" state vs. the "no drop"
  6597.    * state.
  6598.    */
  6599.   onDragOver: function BMDH_onDragOver(event, flavor, session) {
  6600.     if (!this.canDrop(event, session))
  6601.       event.dataTransfer.effectAllowed = "none";
  6602.   },
  6603.  
  6604.   /**
  6605.    * Advertises the set of data types that can be dropped on the Bookmarks
  6606.    * Menu
  6607.    * @returns a FlavourSet object per nsDragAndDrop parlance.
  6608.    */
  6609.   getSupportedFlavours: function BMDH_getSupportedFlavours() {
  6610.     var view = document.getElementById("bookmarksMenuPopup");
  6611.     return view.getSupportedFlavours();
  6612.   },
  6613.  
  6614.   /**
  6615.    * Determine whether or not the user can drop on the Bookmarks Menu.
  6616.    * @param   event
  6617.    *          A dragover event
  6618.    * @param   session
  6619.    *          The active DragSession
  6620.    * @returns true if the user can drop onto the Bookmarks Menu item, false 
  6621.    *          otherwise.
  6622.    */
  6623.   canDrop: function BMDH_canDrop(event, session) {
  6624.     PlacesControllerDragHelper.currentDataTransfer = event.dataTransfer;
  6625.  
  6626.     var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1);  
  6627.     return ip && PlacesControllerDragHelper.canDrop(ip);
  6628.   },
  6629.  
  6630.   /**
  6631.    * Called when the user drops onto the top level Bookmarks Menu item.
  6632.    * @param   event
  6633.    *          A drop event
  6634.    * @param   data
  6635.    *          Data that was dropped
  6636.    * @param   session
  6637.    *          The active DragSession
  6638.    */
  6639.   onDrop: function BMDH_onDrop(event, data, session) {
  6640.     PlacesControllerDragHelper.currentDataTransfer = event.dataTransfer;
  6641.  
  6642.   // Put the item at the end of bookmark menu
  6643.     var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1,
  6644.                                 Ci.nsITreeView.DROP_ON);
  6645.     PlacesControllerDragHelper.onDrop(ip);
  6646.   },
  6647.  
  6648.   /**
  6649.    * Called when drop target leaves the menu or after a drop.
  6650.    * @param   aEvent
  6651.    *          A drop event
  6652.    */
  6653.   onDragExit: function BMDH_onDragExit(event, session) {
  6654.     PlacesControllerDragHelper.currentDataTransfer = null;
  6655.   }
  6656. };
  6657.  
  6658. /**
  6659.  * Handles special drag and drop functionality for menus on the Bookmarks 
  6660.  * Toolbar and Bookmarks Menu.
  6661.  */
  6662. var PlacesMenuDNDController = {
  6663.   _springLoadDelay: 350, // milliseconds
  6664.  
  6665.   /**
  6666.    * All Drag Timers set for the Places UI
  6667.    */
  6668.   _timers: { },
  6669.   
  6670.   /**
  6671.    * Called when the user drags over the Bookmarks top level <menu> element.
  6672.    * @param   event
  6673.    *          The DragEnter event that spawned the opening. 
  6674.    */
  6675.   onBookmarksMenuDragEnter: function PMDC_onDragEnter(event) {
  6676.     if ("loadTime" in this._timers) 
  6677.       return;
  6678.     
  6679.     this._setDragTimer("loadTime", this._openBookmarksMenu, 
  6680.                        this._springLoadDelay, [event]);
  6681.   },
  6682.   
  6683.   /**
  6684.    * Creates a timer that will fire during a drag and drop operation.
  6685.    * @param   id
  6686.    *          The identifier of the timer being set
  6687.    * @param   callback
  6688.    *          The function to call when the timer "fires"
  6689.    * @param   delay
  6690.    *          The time to wait before calling the callback function
  6691.    * @param   args
  6692.    *          An array of arguments to pass to the callback function
  6693.    */
  6694.   _setDragTimer: function PMDC__setDragTimer(id, callback, delay, args) {
  6695.     if (!this._dragSupported)
  6696.       return;
  6697.  
  6698.     // Cancel this timer if it's already running.
  6699.     if (id in this._timers)
  6700.       this._timers[id].cancel();
  6701.       
  6702.     /**
  6703.      * An object implementing nsITimerCallback that calls a user-supplied
  6704.      * method with the specified args in the context of the supplied object.
  6705.      */
  6706.     function Callback(object, method, args) {
  6707.       this._method = method;
  6708.       this._args = args;
  6709.       this._object = object;
  6710.     }
  6711.     Callback.prototype = {
  6712.       notify: function C_notify(timer) {
  6713.         this._method.apply(this._object, this._args);
  6714.       }
  6715.     };
  6716.     
  6717.     var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  6718.     timer.initWithCallback(new Callback(this, callback, args), delay, 
  6719.                            timer.TYPE_ONE_SHOT);
  6720.     this._timers[id] = timer;
  6721.   },
  6722.   
  6723.   /**
  6724.    * Determines if a XUL element represents a container in the Bookmarks system
  6725.    * @returns true if the element is a container element (menu or 
  6726.    *`         menu-toolbarbutton), false otherwise.
  6727.    */
  6728.   _isContainer: function PMDC__isContainer(node) {
  6729.     return node.localName == "menu" ||
  6730.            (node.localName == "toolbarbutton" &&
  6731.             node.getAttribute("type") == "menu");
  6732.   },
  6733.   
  6734.   /**
  6735.    * Opens the Bookmarks Menu when it is dragged over. (This is special-cased, 
  6736.    * since the toplevel Bookmarks <menu> is not a member of an existing places
  6737.    * container, as folders on the personal toolbar or submenus are. 
  6738.    * @param   event
  6739.    *          The DragEnter event that spawned the opening. 
  6740.    */
  6741.   _openBookmarksMenu: function PMDC__openBookmarksMenu(event) {
  6742.     if ("loadTime" in this._timers)
  6743.       delete this._timers.loadTime;
  6744.     if (event.target.id == "bookmarksMenu") {
  6745.       // If this is the bookmarks menu, tell its menupopup child to show.
  6746.       event.target.lastChild.setAttribute("autoopened", "true");
  6747.       event.target.lastChild.showPopup(event.target.lastChild);
  6748.     }  
  6749.   },
  6750.  
  6751.   // Whether or not drag and drop to menus is supported on this platform
  6752.   // Dragging in menus is disabled on OS X due to various repainting issues.
  6753. //@line 953 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-places.js"
  6754.   _dragSupported: true
  6755. //@line 955 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-places.js"
  6756. };
  6757.  
  6758. var PlacesStarButton = {
  6759.   init: function PSB_init() {
  6760.     try {
  6761.       PlacesUtils.bookmarks.addObserver(this, false);
  6762.     } catch(ex) {
  6763.       Components.utils.reportError("PlacesStarButton.init(): error adding bookmark observer: " + ex);
  6764.     }
  6765.   },
  6766.  
  6767.   uninit: function PSB_uninit() {
  6768.     PlacesUtils.bookmarks.removeObserver(this);
  6769.   },
  6770.  
  6771.   QueryInterface: function PSB_QueryInterface(aIID) {
  6772.     if (aIID.equals(Ci.nsINavBookmarkObserver) ||
  6773.         aIID.equals(Ci.nsISupports))
  6774.       return this;
  6775.  
  6776.     throw Cr.NS_NOINTERFACE;
  6777.   },
  6778.  
  6779.   _starred: false,
  6780.   _batching: false,
  6781.  
  6782.   updateState: function PSB_updateState() {
  6783.     var starIcon = document.getElementById("star-button");
  6784.     if (!starIcon)
  6785.       return;
  6786.  
  6787.     var browserBundle = document.getElementById("bundle_browser");
  6788.     var uri = getBrowser().currentURI;
  6789.     this._starred = uri && (PlacesUtils.getMostRecentBookmarkForURI(uri) != -1 ||
  6790.                             PlacesUtils.getMostRecentFolderForFeedURI(uri) != -1);
  6791.     if (this._starred) {
  6792.       starIcon.setAttribute("starred", "true");
  6793.       starIcon.setAttribute("tooltiptext", browserBundle.getString("starButtonOn.tooltip"));
  6794.     }
  6795.     else {
  6796.       starIcon.removeAttribute("starred");
  6797.       starIcon.setAttribute("tooltiptext", browserBundle.getString("starButtonOff.tooltip"));
  6798.     }
  6799.   },
  6800.  
  6801.   onClick: function PSB_onClick(aEvent) {
  6802.     if (aEvent.button == 0)
  6803.       PlacesCommandHook.bookmarkCurrentPage(this._starred);
  6804.  
  6805.     // don't bubble to the textbox so that the address won't be selected
  6806.     aEvent.stopPropagation();
  6807.   },
  6808.  
  6809.   // nsINavBookmarkObserver  
  6810.   onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {
  6811.     this._batching = true;
  6812.   },
  6813.  
  6814.   onEndUpdateBatch: function PSB_onEndUpdateBatch() {
  6815.     this.updateState();
  6816.     this._batching = false;
  6817.   },
  6818.   
  6819.   onItemAdded: function PSB_onItemAdded(aItemId, aFolder, aIndex) {
  6820.     if (!this._batching && !this._starred)
  6821.       this.updateState();
  6822.   },
  6823.  
  6824.   onItemRemoved: function PSB_onItemRemoved(aItemId, aFolder, aIndex) {
  6825.     if (!this._batching)
  6826.       this.updateState();
  6827.   },
  6828.  
  6829.   onItemChanged: function PSB_onItemChanged(aItemId, aProperty,
  6830.                                             aIsAnnotationProperty, aValue) {
  6831.     if (!this._batching && aProperty == "uri")
  6832.       this.updateState();
  6833.   },
  6834.  
  6835.   onItemVisited: function() { },
  6836.   onItemMoved: function() { }
  6837. };
  6838. //@line 6257 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  6839.  
  6840. /*
  6841. //@line 41 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-textZoom.js"
  6842.  */
  6843.  
  6844. // One of the possible values for the mousewheel.* preferences.
  6845. // From nsEventStateManager.cpp.
  6846. const MOUSE_SCROLL_ZOOM = 3;
  6847.  
  6848. /**
  6849.  * Controls the "full zoom" setting and its site-specific preferences.
  6850.  */
  6851. var FullZoom = {
  6852.  
  6853.   //**************************************************************************//
  6854.   // Name & Values
  6855.  
  6856.   // The name of the setting.  Identifies the setting in the prefs database.
  6857.   name: "browser.content.full-zoom",
  6858.  
  6859.   // The global value (if any) for the setting.  Lazily loaded from the service
  6860.   // when first requested, then updated by the pref change listener as it changes.
  6861.   // If there is no global value, then this should be undefined.
  6862.   get globalValue FullZoom_get_globalValue() {
  6863.     var globalValue = this._cps.getPref(null, this.name);
  6864.     if (typeof globalValue != "undefined")
  6865.       globalValue = this._ensureValid(globalValue);
  6866.     delete this.globalValue;
  6867.     return this.globalValue = globalValue;
  6868.   },
  6869.  
  6870.  
  6871.   //**************************************************************************//
  6872.   // Convenience Getters
  6873.  
  6874.   // Content Pref Service
  6875.   get _cps FullZoom_get__cps() {
  6876.     delete this._cps;
  6877.     return this._cps = Cc["@mozilla.org/content-pref/service;1"].
  6878.                        getService(Ci.nsIContentPrefService);
  6879.   },
  6880.  
  6881.   get _prefBranch FullZoom_get__prefBranch() {
  6882.     delete this._prefBranch;
  6883.     return this._prefBranch = Cc["@mozilla.org/preferences-service;1"].
  6884.                               getService(Ci.nsIPrefBranch2);
  6885.   },
  6886.  
  6887.   // browser.zoom.siteSpecific preference cache
  6888.   _siteSpecificPref: undefined,
  6889.  
  6890.   // browser.zoom.updateBackgroundTabs preference cache
  6891.   updateBackgroundTabs: undefined,
  6892.  
  6893.   // whether we are in private browsing mode
  6894.   _inPrivateBrowsing: false,
  6895.  
  6896.   get siteSpecific FullZoom_get_siteSpecific() {
  6897.     return !this._inPrivateBrowsing && this._siteSpecificPref;
  6898.   },
  6899.  
  6900.   //**************************************************************************//
  6901.   // nsISupports
  6902.  
  6903.   // We can't use the Ci shortcut here because it isn't defined yet.
  6904.   interfaces: [Components.interfaces.nsIDOMEventListener,
  6905.                Components.interfaces.nsIObserver,
  6906.                Components.interfaces.nsIContentPrefObserver,
  6907.                Components.interfaces.nsISupportsWeakReference,
  6908.                Components.interfaces.nsISupports],
  6909.  
  6910.   QueryInterface: function FullZoom_QueryInterface(aIID) {
  6911.     if (!this.interfaces.some(function (v) aIID.equals(v)))
  6912.       throw Cr.NS_ERROR_NO_INTERFACE;
  6913.     return this;
  6914.   },
  6915.  
  6916.  
  6917.   //**************************************************************************//
  6918.   // Initialization & Destruction
  6919.  
  6920.   init: function FullZoom_init() {
  6921.     // Listen for scrollwheel events so we can save scrollwheel-based changes.
  6922.     window.addEventListener("DOMMouseScroll", this, false);
  6923.  
  6924.     // Register ourselves with the service so we know when our pref changes.
  6925.     this._cps.addObserver(this.name, this);
  6926.  
  6927.     // We disable site-specific preferences in Private Browsing mode, because the
  6928.     // content preferences module is disabled
  6929.     let os = Cc["@mozilla.org/observer-service;1"].
  6930.              getService(Ci.nsIObserverService);
  6931.     os.addObserver(this, "private-browsing", true);
  6932.  
  6933.     // Retrieve the initial status of the Private Browsing mode.
  6934.     this._inPrivateBrowsing = Cc["@mozilla.org/privatebrowsing;1"].
  6935.                               getService(Ci.nsIPrivateBrowsingService).
  6936.                               privateBrowsingEnabled;
  6937.  
  6938.     this._siteSpecificPref =
  6939.       this._prefBranch.getBoolPref("browser.zoom.siteSpecific");
  6940.     this.updateBackgroundTabs = 
  6941.       this._prefBranch.getBoolPref("browser.zoom.updateBackgroundTabs");
  6942.     // Listen for changes to the browser.zoom branch so we can enable/disable
  6943.     // updating background tabs and per-site saving and restoring of zoom levels.
  6944.     this._prefBranch.addObserver("browser.zoom.", this, true);
  6945.   },
  6946.  
  6947.   destroy: function FullZoom_destroy() {
  6948.     let os = Cc["@mozilla.org/observer-service;1"].
  6949.              getService(Ci.nsIObserverService);
  6950.     os.removeObserver(this, "private-browsing");
  6951.     this._prefBranch.removeObserver("browser.zoom.", this);
  6952.     this._cps.removeObserver(this.name, this);
  6953.     window.removeEventListener("DOMMouseScroll", this, false);
  6954.     delete this._cps;
  6955.   },
  6956.  
  6957.  
  6958.   //**************************************************************************//
  6959.   // Event Handlers
  6960.  
  6961.   // nsIDOMEventListener
  6962.  
  6963.   handleEvent: function FullZoom_handleEvent(event) {
  6964.     switch (event.type) {
  6965.       case "DOMMouseScroll":
  6966.         this._handleMouseScrolled(event);
  6967.         break;
  6968.     }
  6969.   },
  6970.  
  6971.   _handleMouseScrolled: function FullZoom__handleMouseScrolled(event) {
  6972.     // Construct the "mousewheel action" pref key corresponding to this event.
  6973.     // Based on nsEventStateManager::GetBasePrefKeyForMouseWheel.
  6974.     var pref = "mousewheel";
  6975.     if (event.axis == event.HORIZONTAL_AXIS)
  6976.       pref += ".horizscroll";
  6977.  
  6978.     if (event.shiftKey)
  6979.       pref += ".withshiftkey";
  6980.     else if (event.ctrlKey)
  6981.       pref += ".withcontrolkey";
  6982.     else if (event.altKey)
  6983.       pref += ".withaltkey";
  6984.     else if (event.metaKey)
  6985.       pref += ".withmetakey";
  6986.     else
  6987.       pref += ".withnokey";
  6988.  
  6989.     pref += ".action";
  6990.  
  6991.     // Don't do anything if this isn't a "zoom" scroll event.
  6992.     var isZoomEvent = false;
  6993.     try {
  6994.       isZoomEvent = (gPrefService.getIntPref(pref) == MOUSE_SCROLL_ZOOM);
  6995.     } catch (e) {}
  6996.     if (!isZoomEvent)
  6997.       return;
  6998.  
  6999.     // XXX Lazily cache all the possible action prefs so we don't have to get
  7000.     // them anew from the pref service for every scroll event?  We'd have to
  7001.     // make sure to observe them so we can update the cache when they change.
  7002.  
  7003.     // We have to call _applySettingToPref in a timeout because we handle
  7004.     // the event before the event state manager has a chance to apply the zoom
  7005.     // during nsEventStateManager::PostHandleEvent.
  7006.     window.setTimeout(function (self) { self._applySettingToPref() }, 0, this);
  7007.   },
  7008.  
  7009.   // nsIObserver
  7010.  
  7011.   observe: function (aSubject, aTopic, aData) {
  7012.     switch(aTopic) {
  7013.       case "nsPref:changed":
  7014.         switch(aData) {
  7015.           case "browser.zoom.siteSpecific":
  7016.             this._siteSpecificPref =
  7017.               this._prefBranch.getBoolPref("browser.zoom.siteSpecific");
  7018.             break;
  7019.           case "browser.zoom.updateBackgroundTabs":
  7020.             this.updateBackgroundTabs =
  7021.               this._prefBranch.getBoolPref("browser.zoom.updateBackgroundTabs");
  7022.             break;
  7023.         }
  7024.         break;
  7025.       case "private-browsing":
  7026.         switch (aData) {
  7027.           case "enter":
  7028.             this._inPrivateBrowsing = true;
  7029.             break;
  7030.           case "exit":
  7031.             this._inPrivateBrowsing = false;
  7032.             break;
  7033.         }
  7034.         break;
  7035.     }
  7036.   },
  7037.  
  7038.   // nsIContentPrefObserver
  7039.  
  7040.   onContentPrefSet: function FullZoom_onContentPrefSet(aGroup, aName, aValue) {
  7041.     if (aGroup == this._cps.grouper.group(gBrowser.currentURI))
  7042.       this._applyPrefToSetting(aValue);
  7043.     else if (aGroup == null) {
  7044.       this.globalValue = this._ensureValid(aValue);
  7045.  
  7046.       // If the current page doesn't have a site-specific preference,
  7047.       // then its zoom should be set to the new global preference now that
  7048.       // the global preference has changed.
  7049.       if (!this._cps.hasPref(gBrowser.currentURI, this.name))
  7050.         this._applyPrefToSetting();
  7051.     }
  7052.   },
  7053.  
  7054.   onContentPrefRemoved: function FullZoom_onContentPrefRemoved(aGroup, aName) {
  7055.     if (aGroup == this._cps.grouper.group(gBrowser.currentURI))
  7056.       this._applyPrefToSetting();
  7057.     else if (aGroup == null) {
  7058.       this.globalValue = undefined;
  7059.  
  7060.       // If the current page doesn't have a site-specific preference,
  7061.       // then its zoom should be set to the default preference now that
  7062.       // the global preference has changed.
  7063.       if (!this._cps.hasPref(gBrowser.currentURI, this.name))
  7064.         this._applyPrefToSetting();
  7065.     }
  7066.   },
  7067.  
  7068.   // location change observer
  7069.  
  7070.   onLocationChange: function FullZoom_onLocationChange(aURI, aBrowser) {
  7071.     if (!aURI)
  7072.       return;
  7073.     this._applyPrefToSetting(this._cps.getPref(aURI, this.name), aBrowser);
  7074.   },
  7075.  
  7076.   // update state of zoom type menu item
  7077.  
  7078.   updateMenu: function FullZoom_updateMenu() {
  7079.     var menuItem = document.getElementById("toggle_zoom");
  7080.  
  7081.     menuItem.setAttribute("checked", !ZoomManager.useFullZoom);
  7082.   },
  7083.  
  7084.   //**************************************************************************//
  7085.   // Setting & Pref Manipulation
  7086.  
  7087.   reduce: function FullZoom_reduce() {
  7088.     ZoomManager.reduce();
  7089.     this._applySettingToPref();
  7090.   },
  7091.  
  7092.   enlarge: function FullZoom_enlarge() {
  7093.     ZoomManager.enlarge();
  7094.     this._applySettingToPref();
  7095.   },
  7096.  
  7097.   reset: function FullZoom_reset() {
  7098.     if (typeof this.globalValue != "undefined")
  7099.       ZoomManager.zoom = this.globalValue;
  7100.     else
  7101.       ZoomManager.reset();
  7102.  
  7103.     this._removePref();
  7104.   },
  7105.  
  7106.   setSettingValue: function FullZoom_setSettingValue() {
  7107.     var value = this._cps.getPref(gBrowser.currentURI, this.name);
  7108.     this._applyPrefToSetting(value);
  7109.   },
  7110.  
  7111.   /**
  7112.    * Set the zoom level for the current tab.
  7113.    *
  7114.    * Per nsPresContext::setFullZoom, we can set the zoom to its current value
  7115.    * without significant impact on performance, as the setting is only applied
  7116.    * if it differs from the current setting.  In fact getting the zoom and then
  7117.    * checking ourselves if it differs costs more.
  7118.    * 
  7119.    * And perhaps we should always set the zoom even if it was more expensive,
  7120.    * since DocumentViewerImpl::SetTextZoom claims that child documents can have
  7121.    * a different text zoom (although it would be unusual), and it implies that
  7122.    * those child text zooms should get updated when the parent zoom gets set,
  7123.    * and perhaps the same is true for full zoom
  7124.    * (although DocumentViewerImpl::SetFullZoom doesn't mention it).
  7125.    *
  7126.    * So when we apply new zoom values to the browser, we simply set the zoom.
  7127.    * We don't check first to see if the new value is the same as the current
  7128.    * one.
  7129.    **/
  7130.   _applyPrefToSetting: function FullZoom__applyPrefToSetting(aValue, aBrowser) {
  7131.     var browser = aBrowser || gBrowser.selectedBrowser;
  7132.  
  7133.     if (!this.siteSpecific || gInPrintPreviewMode ||
  7134.         browser.contentDocument instanceof Ci.nsIImageDocument)
  7135.       return;
  7136.  
  7137.     try {
  7138.       if (typeof aValue != "undefined")
  7139.         ZoomManager.setZoomForBrowser(browser, this._ensureValid(aValue));
  7140.       else if (typeof this.globalValue != "undefined")
  7141.         ZoomManager.setZoomForBrowser(browser, this.globalValue);
  7142.       else
  7143.         ZoomManager.setZoomForBrowser(browser, 1);
  7144.     }
  7145.     catch(ex) {}
  7146.   },
  7147.  
  7148.   _applySettingToPref: function FullZoom__applySettingToPref() {
  7149.     if (!this.siteSpecific || gInPrintPreviewMode ||
  7150.         content.document instanceof Ci.nsIImageDocument)
  7151.       return;
  7152.  
  7153.     var zoomLevel = ZoomManager.zoom;
  7154.     this._cps.setPref(gBrowser.currentURI, this.name, zoomLevel);
  7155.   },
  7156.  
  7157.   _removePref: function FullZoom__removePref() {
  7158.     if (!(content.document instanceof Ci.nsIImageDocument))
  7159.       this._cps.removePref(gBrowser.currentURI, this.name);
  7160.   },
  7161.  
  7162.  
  7163.   //**************************************************************************//
  7164.   // Utilities
  7165.  
  7166.   _ensureValid: function FullZoom__ensureValid(aValue) {
  7167.     if (isNaN(aValue))
  7168.       return 1;
  7169.  
  7170.     if (aValue < ZoomManager.MIN)
  7171.       return ZoomManager.MIN;
  7172.  
  7173.     if (aValue > ZoomManager.MAX)
  7174.       return ZoomManager.MAX;
  7175.  
  7176.     return aValue;
  7177.   }
  7178. };
  7179. //@line 6259 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  7180.  
  7181. /*
  7182. //@line 39 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser-tabPreviews.js"
  7183.  */
  7184.  
  7185. /**
  7186.  * Tab previews utility, produces thumbnails
  7187.  */
  7188. var tabPreviews = {
  7189.   aspectRatio: 0.5625, // 16:9
  7190.   init: function tabPreviews__init() {
  7191.     this.width = Math.ceil(screen.availWidth / 5);
  7192.     this.height = Math.round(this.width * this.aspectRatio);
  7193.  
  7194.     gBrowser.tabContainer.addEventListener("TabSelect", this, false);
  7195.     gBrowser.tabContainer.addEventListener("SSTabRestored", this, false);
  7196.   },
  7197.   uninit: function tabPreviews__uninit() {
  7198.     gBrowser.tabContainer.removeEventListener("TabSelect", this, false);
  7199.     gBrowser.tabContainer.removeEventListener("SSTabRestored", this, false);
  7200.     this._selectedTab = null;
  7201.   },
  7202.   get: function tabPreviews__get(aTab) {
  7203.     if (aTab.__thumbnail_lastURI &&
  7204.         aTab.__thumbnail_lastURI != aTab.linkedBrowser.currentURI.spec) {
  7205.       aTab.__thumbnail = null;
  7206.       aTab.__thumbnail_lastURI = null;
  7207.     }
  7208.     return aTab.__thumbnail || this.capture(aTab, !aTab.hasAttribute("busy"));
  7209.   },
  7210.   capture: function tabPreviews__capture(aTab, aStore) {
  7211.     var thumbnail = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
  7212.     thumbnail.mozOpaque = true;
  7213.     thumbnail.height = this.height;
  7214.     thumbnail.width = this.width;
  7215.  
  7216.     var ctx = thumbnail.getContext("2d");
  7217.     var win = aTab.linkedBrowser.contentWindow;
  7218.     var snippetWidth = win.innerWidth * .6;
  7219.     var scale = this.width / snippetWidth;
  7220.     ctx.scale(scale, scale);
  7221.     ctx.drawWindow(win, win.scrollX, win.scrollY,
  7222.                    snippetWidth, snippetWidth * this.aspectRatio, "rgb(255,255,255)");
  7223.  
  7224.     if (aStore) {
  7225.       aTab.__thumbnail = thumbnail;
  7226.       aTab.__thumbnail_lastURI = aTab.linkedBrowser.currentURI.spec;
  7227.     }
  7228.     return thumbnail;
  7229.   },
  7230.   handleEvent: function tabPreviews__handleEvent(event) {
  7231.     switch (event.type) {
  7232.       case "TabSelect":
  7233.         if (this._selectedTab &&
  7234.             this._selectedTab.parentNode &&
  7235.             !this._pendingUpdate) {
  7236.           // Generate a thumbnail for the tab that was selected.
  7237.           // The timeout keeps the UI snappy and prevents us from generating thumbnails
  7238.           // for tabs that will be closed. During that timeout, don't generate other
  7239.           // thumbnails in case multiple TabSelect events occur fast in succession.
  7240.           this._pendingUpdate = true;
  7241.           setTimeout(function (self, aTab) {
  7242.             self._pendingUpdate = false;
  7243.             if (aTab.parentNode && !aTab.hasAttribute("busy"))
  7244.               self.capture(aTab, true);
  7245.           }, 2000, this, this._selectedTab);
  7246.         }
  7247.         this._selectedTab = event.target;
  7248.         break;
  7249.       case "SSTabRestored":
  7250.         this.capture(event.target, true);
  7251.         break;
  7252.     }
  7253.   }
  7254. };
  7255.  
  7256. /**
  7257.  * Ctrl-Tab panel
  7258.  */
  7259. var ctrlTab = {
  7260.   get panel () {
  7261.     delete this.panel;
  7262.     return this.panel = document.getElementById("ctrlTab-panel");
  7263.   },
  7264.   get searchField () {
  7265.     delete this.searchField;
  7266.     return this.searchField = document.getElementById("ctrlTab-search");
  7267.   },
  7268.   get pagesBar () {
  7269.     delete this.pagesBar;
  7270.     return this.pagesBar = document.getElementById("ctrlTab-pages");
  7271.   },
  7272.   get thumbnails () {
  7273.     delete this.thumbnails;
  7274.     return this.thumbnails = this.panel.getElementsByClassName("ctrlTab-thumbnail");
  7275.   },
  7276.   get columns () {
  7277.     delete this.columns;
  7278.     return this.columns = this.thumbnails.length /
  7279.                           this.panel.getElementsByClassName("ctrlTab-row").length;
  7280.   },
  7281.   get closeCharCode () {
  7282.     delete this.closeCharCode;
  7283.     return this.closeCharCode = document.getElementById("key_close")
  7284.                                         .getAttribute("key")
  7285.                                         .toLocaleLowerCase().charCodeAt(0);
  7286.   },
  7287.   get findCharCode () {
  7288.     delete this.findCharCode;
  7289.     return this.findCharCode = document.getElementById("key_find")
  7290.                                        .getAttribute("key")
  7291.                                        .toLocaleLowerCase().charCodeAt(0);
  7292.   },
  7293.   get recentlyUsedLimit () {
  7294.     delete this.recentlyUsedLimit;
  7295.     return this.recentlyUsedLimit = gPrefService.getIntPref("browser.ctrlTab.recentlyUsedLimit");
  7296.   },
  7297.   selectedIndex: 0,
  7298.   get selected () this.thumbnails.item(this.selectedIndex),
  7299.   get isOpen   () this.panel.state == "open" || this.panel.state == "showing",
  7300.   get tabCount () this.tabList.length,
  7301.  
  7302.   get sticky () this.panel.hasAttribute("sticky"),
  7303.   set sticky (val) {
  7304.     if (val)
  7305.       this.panel.setAttribute("sticky", "true");
  7306.     else
  7307.       this.panel.removeAttribute("sticky");
  7308.     return val;
  7309.   },
  7310.  
  7311.   get pages () Math.ceil(this.tabCount / this.thumbnails.length),
  7312.   get page  () this._page || 0,
  7313.   set page  (page) {
  7314.     if (page < 0)
  7315.       page = this.pages - 1;
  7316.     else if (page >= this.pages)
  7317.       page = 0;
  7318.  
  7319.     if (this.pagesBar.childNodes.length) {
  7320.       this.pagesBar.childNodes[this.page].removeAttribute("selected");
  7321.       this.pagesBar.childNodes[page].setAttribute("selected", "true");
  7322.     }
  7323.  
  7324.     this._page = page;
  7325.     this.updatePreviews();
  7326.     return page;
  7327.   },
  7328.  
  7329.   get tabList () {
  7330.     if (this._tabList)
  7331.       return this._tabList;
  7332.  
  7333.     var list = Array.slice(gBrowser.mTabs);
  7334.  
  7335.     if (this._closing)
  7336.       this.detachTab(this._closing, list);
  7337.  
  7338.     for (let i = 0; i < gBrowser.tabContainer.selectedIndex; i++)
  7339.       list.push(list.shift());
  7340.  
  7341.     if (!this._useTabBarOrder && this.recentlyUsedLimit != 0) {
  7342.       let recentlyUsedTabs = this._recentlyUsedTabs;
  7343.       if (this.recentlyUsedLimit > 0)
  7344.         recentlyUsedTabs = this._recentlyUsedTabs.slice(0, this.recentlyUsedLimit);
  7345.       for (let i = recentlyUsedTabs.length - 1; i >= 0; i--) {
  7346.         list.splice(list.indexOf(recentlyUsedTabs[i]), 1);
  7347.         list.unshift(recentlyUsedTabs[i]);
  7348.       }
  7349.     }
  7350.  
  7351.     if (this.searchField.value) {
  7352.       list = list.filter(function (tab) {
  7353.         let lowerCaseLabel, uri;
  7354.         for (let i = 0; i < this.length; i++) {
  7355.           if (tab.label.indexOf(this[i]) != -1)
  7356.             continue;
  7357.  
  7358.           if (!lowerCaseLabel)
  7359.             lowerCaseLabel = tab.label.toLocaleLowerCase();
  7360.           if (lowerCaseLabel.indexOf(this[i]) != -1)
  7361.             continue;
  7362.  
  7363.           if (!uri) {
  7364.             uri = tab.linkedBrowser.currentURI.spec;
  7365.             try {
  7366.               uri = decodeURI(uri);
  7367.             } catch (e) {}
  7368.           }
  7369.           if (uri.indexOf(this[i]) != -1)
  7370.             continue;
  7371.  
  7372.           return false;
  7373.         }
  7374.         return true;
  7375.       }, this.searchField.value.split(/\s+/g));
  7376.     }
  7377.  
  7378.     return this._tabList = list;
  7379.   },
  7380.  
  7381.   init: function ctrlTab__init() {
  7382.     if (this._recentlyUsedTabs)
  7383.       return;
  7384.     this._recentlyUsedTabs = [gBrowser.selectedTab];
  7385.  
  7386.     var tabContainer = gBrowser.tabContainer;
  7387.     tabContainer.addEventListener("TabOpen", this, false);
  7388.     tabContainer.addEventListener("TabSelect", this, false);
  7389.     tabContainer.addEventListener("TabClose", this, false);
  7390.  
  7391.     this._handleCtrlTab =
  7392.       gPrefService.getBoolPref("browser.ctrlTab.previews") &&
  7393.       (!gPrefService.prefHasUserValue("browser.ctrlTab.disallowForScreenReaders") ||
  7394.        !gPrefService.getBoolPref("browser.ctrlTab.disallowForScreenReaders"));
  7395.     if (this._handleCtrlTab)
  7396.       gBrowser.mTabBox.handleCtrlTab = false;
  7397.     document.addEventListener("keypress", this, false);
  7398.   },
  7399.  
  7400.   uninit: function ctrlTab__uninit() {
  7401.     this._recentlyUsedTabs = null;
  7402.  
  7403.     var tabContainer = gBrowser.tabContainer;
  7404.     tabContainer.removeEventListener("TabOpen", this, false);
  7405.     tabContainer.removeEventListener("TabSelect", this, false);
  7406.     tabContainer.removeEventListener("TabClose", this, false);
  7407.  
  7408.     this.panel.removeEventListener("popuphiding", this, false);
  7409.     this.panel.removeEventListener("popupshown", this, false);
  7410.     this.panel.removeEventListener("popuphidden", this, false);
  7411.     document.removeEventListener("keypress", this, false);
  7412.     if (this._handleCtrlTab)
  7413.       gBrowser.mTabBox.handleCtrlTab = true;
  7414.   },
  7415.  
  7416.   search: function ctrlTab__search() {
  7417.     if (this.isOpen) {
  7418.       this._tabList = null;
  7419.       this.buildPagesBar();
  7420.       this.goToPage(0, 0);
  7421.       this.updatePreviews();
  7422.     }
  7423.   },
  7424.  
  7425.   buildPagesBar: function ctrlTab__buildPagesBar() {
  7426.     var pages = this.pages;
  7427.     if (pages == 1)
  7428.       pages = 0;
  7429.     while (this.pagesBar.childNodes.length > pages)
  7430.       this.pagesBar.removeChild(this.pagesBar.lastChild);
  7431.     while (this.pagesBar.childNodes.length < pages) {
  7432.       let pointer = document.createElement("spacer");
  7433.       pointer.setAttribute("onclick", "ctrlTab.goToPage(" + this.pagesBar.childNodes.length + ");");
  7434.       pointer.setAttribute("class", "ctrlTab-pagePointer");
  7435.       this.pagesBar.appendChild(pointer);
  7436.     }
  7437.   },
  7438.  
  7439.   goToPage: function ctrlTab__goToPage(aPage, aIndex) {
  7440.     this.page = aPage;
  7441.     this.selected.removeAttribute("selected");
  7442.     if (aIndex) {
  7443.       this.selectedIndex = aIndex;
  7444.       while (!this.selected || !this.selected.hasAttribute("valid"))
  7445.         this.selectedIndex--;
  7446.     } else {
  7447.       this.selectedIndex = 0;
  7448.     }
  7449.     this.updateSelected();
  7450.   },
  7451.  
  7452.   updatePreviews: function ctrlTab__updatePreviews() {
  7453.     var tabs = this.tabList;
  7454.     var offset = this.page * this.thumbnails.length;
  7455.     for (let i = 0; i < this.thumbnails.length; i++)
  7456.       this.updatePreview(this.thumbnails[i], tabs[i + offset]);
  7457.   },
  7458.   updatePreview: function ctrlTab__updatePreview(aThumbnail, aTab) {
  7459.     do {
  7460.       if (aThumbnail._tab) {
  7461.         if (aThumbnail._tab == aTab)
  7462.           break;
  7463.         aThumbnail._tab.removeEventListener("DOMAttrModified", this, false);
  7464.       }
  7465.       aThumbnail._tab = aTab;
  7466.       if (aTab)
  7467.         aTab.addEventListener("DOMAttrModified", this, false);
  7468.     } while (false);
  7469.  
  7470.     if (aThumbnail.firstChild)
  7471.       aThumbnail.removeChild(aThumbnail.firstChild);
  7472.     if (aTab) {
  7473.       aThumbnail.appendChild(tabPreviews.get(aTab));
  7474.       aThumbnail.setAttribute("valid", "true");
  7475.       aThumbnail.setAttribute("label", aTab.label);
  7476.       aThumbnail.setAttribute("crop", aTab.crop);
  7477.     } else {
  7478.       let placeholder = document.createElement("hbox");
  7479.       placeholder.height = tabPreviews.height;
  7480.       aThumbnail.appendChild(placeholder);
  7481.       aThumbnail.removeAttribute("valid");
  7482.       aThumbnail.setAttribute("label", "placeholder");
  7483.     }
  7484.     aThumbnail.width = tabPreviews.width;
  7485.   },
  7486.  
  7487.   tabAttrModified: function ctrlTab__tabAttrModified(aTab, aAttrName) {
  7488.     switch (aAttrName) {
  7489.       case "label":
  7490.       case "crop":
  7491.       case "busy":
  7492.         for (let i = this.thumbnails.length - 1; i >= 0; i--) {
  7493.           if (this.thumbnails[i]._tab == aTab) {
  7494.             this.updatePreview(this.thumbnails[i], aTab);
  7495.             break;
  7496.           }
  7497.         }
  7498.         break;
  7499.     }
  7500.   },
  7501.  
  7502.   advanceSelected: function ctrlTab__advanceSelected() {
  7503.     this.selected.removeAttribute("selected");
  7504.  
  7505.     this.selectedIndex += this.invertDirection ? -1 : 1;
  7506.     if (this.selectedIndex < 0) {
  7507.       this.page--;
  7508.       this.selectedIndex = this.thumbnails.length - 1;
  7509.       while (!this.selected.hasAttribute("valid"))
  7510.         this.selectedIndex--;
  7511.     } else if (this.selectedIndex >= this.thumbnails.length || !this.selected.hasAttribute("valid")) {
  7512.       this.page++;
  7513.       this.selectedIndex = 0;
  7514.     }
  7515.     this.updateSelected();
  7516.   },
  7517.  
  7518.   updateSelected: function ctrlTab__updateSelected() {
  7519.     if (this.tabCount)
  7520.       this.selected.setAttribute("selected", "true");
  7521.   },
  7522.  
  7523.   selectThumbnail: function ctrlTab__selectThumbnail(aThumbnail) {
  7524.     if (this.tabCount) {
  7525.       this._tabToSelect = (aThumbnail || this.selected)._tab;
  7526.       this.panel.hidePopup();
  7527.     }
  7528.   },
  7529.  
  7530.   attachTab: function ctrlTab__attachTab(aTab, aPos) {
  7531.     if (aPos == 0)
  7532.       this._recentlyUsedTabs.unshift(aTab);
  7533.     else if (aPos)
  7534.       this._recentlyUsedTabs.splice(aPos, 0, aTab);
  7535.     else
  7536.       this._recentlyUsedTabs.push(aTab);
  7537.   },
  7538.   detachTab: function ctrlTab__detachTab(aTab, aTabs) {
  7539.     var tabs = aTabs || this._recentlyUsedTabs;
  7540.     var i = tabs.indexOf(aTab);
  7541.     if (i >= 0)
  7542.       tabs.splice(i, 1);
  7543.   },
  7544.  
  7545.   open: function ctrlTab__open(aSticky) {
  7546.     if (this.isOpen && this.sticky) {
  7547.       this.panel.hidePopup();
  7548.       return;
  7549.     }
  7550.     this.sticky = !!aSticky;
  7551.  
  7552.     this._deferOnTabSelect = [];
  7553.     if (this.invertDirection)
  7554.       this._useTabBarOrder = true;
  7555.  
  7556.     this._tabBarHandlesCtrlPageUpDown = gBrowser.mTabBox.handleCtrlPageUpDown;
  7557.     gBrowser.mTabBox.handleCtrlPageUpDown = false;
  7558.  
  7559.     document.addEventListener("keyup", this, true);
  7560.     document.addEventListener("keydown", this, true);
  7561.     this.panel.addEventListener("popupshown", this, false);
  7562.     this.panel.addEventListener("popuphiding", this, false);
  7563.     this.panel.addEventListener("popuphidden", this, false);
  7564.     this._prevFocus = document.commandDispatcher.focusedElement ||
  7565.                       document.commandDispatcher.focusedWindow;
  7566.     this.panel.hidden = false;
  7567.     this.panel.width = screen.availWidth * .85;
  7568.     this.panel.popupBoxObject.setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  7569.     this.panel.openPopupAtScreen(screen.availLeft + (screen.availWidth - this.panel.width) / 2,
  7570.                                  screen.availTop + screen.availHeight * .12,
  7571.                                  false);
  7572.     this.buildPagesBar();
  7573.     this.selectedIndex = 0;
  7574.     this.page = 0;
  7575.     this.advanceSelected();
  7576.   },
  7577.  
  7578.   onKeyPress: function ctrlTab__onKeyPress(event) {
  7579.     var isOpen = this.isOpen;
  7580.  
  7581.     if (isOpen &&
  7582.         event.target == this.searchField &&
  7583.         event.keyCode != event.DOM_VK_ESCAPE)
  7584.       return;
  7585.  
  7586.     if (isOpen) {
  7587.       event.preventDefault();
  7588.       event.stopPropagation();
  7589.     }
  7590.  
  7591.     switch (event.keyCode) {
  7592.       case event.DOM_VK_TAB:
  7593.         if ((event.ctrlKey || this.sticky) && !event.altKey && !event.metaKey) {
  7594.           this.invertDirection = event.shiftKey;
  7595.           if (isOpen) {
  7596.             this.advanceSelected();
  7597.           } else if (this._handleCtrlTab) {
  7598.             event.preventDefault();
  7599.             event.stopPropagation();
  7600.             if (gBrowser.mTabs.length > 2) {
  7601.               this.open();
  7602.             } else if (gBrowser.mTabs.length == 2) {
  7603.               gBrowser.selectedTab = gBrowser.selectedTab.nextSibling ||
  7604.                                      gBrowser.selectedTab.previousSibling;
  7605.             }
  7606.           }
  7607.         }
  7608.         break;
  7609.       case event.DOM_VK_UP:
  7610.         if (isOpen) {
  7611.           let index = this.selectedIndex - this.columns;
  7612.           if (index < 0) {
  7613.             this.goToPage(this.page - 1, this.thumbnails.length + index);
  7614.           } else {
  7615.             this.selected.removeAttribute("selected");
  7616.             this.selectedIndex = index;
  7617.             this.updateSelected();
  7618.           }
  7619.         }
  7620.         break;
  7621.       case event.DOM_VK_DOWN:
  7622.         if (isOpen) {
  7623.           let index = this.selectedIndex + this.columns;
  7624.           if (index >= this.thumbnails.length || !this.thumbnails[index].hasAttribute("valid")) {
  7625.             this.goToPage(this.page + 1, this.selectedIndex % this.columns);
  7626.           } else {
  7627.             this.selected.removeAttribute("selected");
  7628.             this.selectedIndex = index;
  7629.             while (!this.selected.hasAttribute("valid"))
  7630.               this.selectedIndex--;
  7631.             this.updateSelected();
  7632.           }
  7633.         }
  7634.         break;
  7635.       case event.DOM_VK_LEFT:
  7636.         if (isOpen) {
  7637.           this.invertDirection = true;
  7638.           this.advanceSelected();
  7639.         }
  7640.         break;
  7641.       case event.DOM_VK_RIGHT:
  7642.         if (isOpen) {
  7643.           this.invertDirection = false;
  7644.           this.advanceSelected();
  7645.         }
  7646.         break;
  7647.       case event.DOM_VK_HOME:
  7648.         if (isOpen)
  7649.           this.goToPage(0);
  7650.         break;
  7651.       case event.DOM_VK_END:
  7652.         if (isOpen)
  7653.           this.goToPage(this.pages - 1, this.thumbnails.length - 1);
  7654.         break;
  7655.       case event.DOM_VK_PAGE_UP:
  7656.         if (isOpen)
  7657.           this.goToPage(this.page - 1);
  7658.         break;
  7659.       case event.DOM_VK_PAGE_DOWN:
  7660.         if (isOpen)
  7661.           this.goToPage(this.page + 1);
  7662.         break;
  7663.       case event.DOM_VK_RETURN:
  7664.         if (isOpen && this.sticky)
  7665.           this.selectThumbnail();
  7666.         break;
  7667.       case event.DOM_VK_ESCAPE:
  7668.         if (isOpen)
  7669.           this.panel.hidePopup();
  7670.         break;
  7671.       default:
  7672.         if (isOpen && event.ctrlKey) {
  7673.           switch (event.charCode) {
  7674.             case this.closeCharCode:
  7675.               gBrowser.removeTab(this.selected._tab);
  7676.               break;
  7677.             case this.findCharCode:
  7678.               this.searchField.focus();
  7679.               break;
  7680.           }
  7681.         }
  7682.     }
  7683.   },
  7684.   onPopupHiding: function ctrlTab__onPopupHiding() {
  7685.     gBrowser.mTabBox.handleCtrlPageUpDown = this._tabBarHandlesCtrlPageUpDown;
  7686.     document.removeEventListener("keyup", this, true);
  7687.     document.removeEventListener("keydown", this, true);
  7688.  
  7689.     this.selected.removeAttribute("selected");
  7690.     if (this.pagesBar.childNodes.length)
  7691.       this.pagesBar.childNodes[this.page].removeAttribute("selected");
  7692.  
  7693.     Array.forEach(this.thumbnails, function (thumbnail) {
  7694.       this.updatePreview(thumbnail, null);
  7695.     }, this);
  7696.  
  7697.     this.searchField.value = "";
  7698.     this.invertDirection = false;
  7699.     this.sticky = false;
  7700.     this._useTabBarOrder = false;
  7701.     this._page = null;
  7702.     this._tabList = null;
  7703.  
  7704.     this._deferOnTabSelect.forEach(this.onTabSelect, this);
  7705.     this._deferOnTabSelect = null;
  7706.  
  7707.     this._prevFocus.focus();
  7708.     this._prevFocus = null;
  7709.  
  7710.     if (this._tabToSelect) {
  7711.       gBrowser.selectedTab = this._tabToSelect;
  7712.       this._tabToSelect = null;
  7713.     }
  7714.   },
  7715.   onTabSelect: function ctrlTab__onTabSelect(aTab) {
  7716.     if (aTab.parentNode) {
  7717.       this.detachTab(aTab);
  7718.       this.attachTab(aTab, 0);
  7719.     }
  7720.   },
  7721.  
  7722.   removeClosingTabFromUI: function ctrlTab__removeClosingTabFromUI(aTab) {
  7723.     this._closing = aTab;
  7724.     this._tabList = null;
  7725.     if (this.tabCount == 1) {
  7726.       this.panel.hidePopup();
  7727.     } else {
  7728.       this.buildPagesBar();
  7729.       this.updatePreviews();
  7730.       if (!this.selected.hasAttribute("valid"))
  7731.         this.advanceSelected();
  7732.       else
  7733.         this.updateSelected();
  7734.     }
  7735.     this._closing = null;
  7736.   },
  7737.  
  7738.   handleEvent: function ctrlTab__handleEvent(event) {
  7739.     switch (event.type) {
  7740.       case "DOMAttrModified":
  7741.         this.tabAttrModified(event.target, event.attrName);
  7742.         break;
  7743.       case "TabSelect":
  7744.         if (this.isOpen)
  7745.           // don't change the tab order while the panel is open
  7746.           this._deferOnTabSelect.push(event.target);
  7747.         else
  7748.           this.onTabSelect(event.target);
  7749.         break;
  7750.       case "TabOpen":
  7751.         this.attachTab(event.target, 1);
  7752.         break;
  7753.       case "TabClose":
  7754.         this.detachTab(event.target);
  7755.         if (this.isOpen)
  7756.           this.removeClosingTabFromUI(event.target);
  7757.         break;
  7758.       case "keypress":
  7759.         this.onKeyPress(event);
  7760.         break;
  7761.       case "keydown":
  7762.       case "keyup":
  7763.         if (event.target == this.searchField) {
  7764.           if (event.keyCode == event.DOM_VK_RETURN) {
  7765.             // If there's a pending search, kick it off now.
  7766.             if (this.searchField._timer)
  7767.               this.search();
  7768.             this.selectThumbnail();
  7769.           }
  7770.         } else {
  7771.           // Manually consume the events, as the panel is open but doesn't
  7772.           // necessarily have focus.
  7773.           event.stopPropagation();
  7774.           event.preventDefault();
  7775.         }
  7776.  
  7777.         if (!this.sticky &&
  7778.             event.type == "keyup" &&
  7779.             event.keyCode == event.DOM_VK_CONTROL)
  7780.           this.selectThumbnail();
  7781.         break;
  7782.       case "popupshown":
  7783.         if (this.sticky && event.target == this.panel)
  7784.           this.searchField.focus();
  7785.         break;
  7786.       case "popuphiding":
  7787.         if (event.target == this.panel)
  7788.           this.onPopupHiding();
  7789.         break;
  7790.       case "popuphidden":
  7791.         if (event.target == this.panel) {
  7792.           // Destroy the widget in order to prevent outdated content
  7793.           // when re-opening the panel.
  7794.           this.panel.hidden = true;
  7795.         }
  7796.         break;
  7797.     }
  7798.   }
  7799. };
  7800. //@line 6261 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  7801.  
  7802. HistoryMenu.toggleRecentlyClosedTabs = function PHM_toggleRecentlyClosedTabs() {
  7803.   // enable/disable the Recently Closed Tabs sub menu
  7804.   var undoPopup = document.getElementById("historyUndoPopup");
  7805.  
  7806.   // no restorable tabs, so disable menu
  7807.   if (this._ss.getClosedTabCount(window) == 0)
  7808.     undoPopup.parentNode.setAttribute("disabled", true);
  7809.   else
  7810.     undoPopup.parentNode.removeAttribute("disabled");
  7811. }
  7812.  
  7813. /**
  7814.  * Populate when the history menu is opened
  7815.  */
  7816. HistoryMenu.populateUndoSubmenu = function PHM_populateUndoSubmenu() {
  7817.   var undoPopup = document.getElementById("historyUndoPopup");
  7818.  
  7819.   // remove existing menu items
  7820.   while (undoPopup.hasChildNodes())
  7821.     undoPopup.removeChild(undoPopup.firstChild);
  7822.  
  7823.   // no restorable tabs, so make sure menu is disabled, and return
  7824.   if (this._ss.getClosedTabCount(window) == 0) {
  7825.     undoPopup.parentNode.setAttribute("disabled", true);
  7826.     return;
  7827.   }
  7828.  
  7829.   // enable menu
  7830.   undoPopup.parentNode.removeAttribute("disabled");
  7831.  
  7832.   // populate menu
  7833.   var undoItems = eval("(" + this._ss.getClosedTabData(window) + ")");
  7834.   for (var i = 0; i < undoItems.length; i++) {
  7835.     var m = document.createElement("menuitem");
  7836.     m.setAttribute("label", undoItems[i].title);
  7837.     if (undoItems[i].image) {
  7838.       let iconURL = undoItems[i].image;
  7839.       // don't initiate a connection just to fetch a favicon (see bug 467828)
  7840.       if (/^https?:/.test(iconURL))
  7841.         iconURL = "moz-anno:favicon:" + iconURL;
  7842.       m.setAttribute("image", iconURL);
  7843.     }
  7844.     m.setAttribute("class", "menuitem-iconic bookmark-item");
  7845.     m.setAttribute("value", i);
  7846.     m.setAttribute("oncommand", "undoCloseTab(" + i + ");");
  7847.     m.addEventListener("click", undoCloseMiddleClick, false);
  7848.     if (i == 0)
  7849.       m.setAttribute("key", "key_undoCloseTab");
  7850.     undoPopup.appendChild(m);
  7851.   }
  7852.  
  7853.   // "Open All in Tabs"
  7854.   var strings = gNavigatorBundle;
  7855.   undoPopup.appendChild(document.createElement("menuseparator"));
  7856.   m = undoPopup.appendChild(document.createElement("menuitem"));
  7857.   m.setAttribute("label", strings.getString("menuOpenAllInTabs.label"));
  7858.   m.setAttribute("accesskey", strings.getString("menuOpenAllInTabs.accesskey"));
  7859.   m.addEventListener("command", function() {
  7860.     for (var i = 0; i < undoItems.length; i++)
  7861.       undoCloseTab();
  7862.   }, false);
  7863. }
  7864.  
  7865. HistoryMenu.toggleRecentlyClosedWindows = function PHM_toggleRecentlyClosedWindows() {
  7866.   // enable/disable the Recently Closed Windows sub menu
  7867.   let undoPopup = document.getElementById("historyUndoWindowPopup");
  7868.  
  7869.   // no restorable windows, so disable menu
  7870.   if (this._ss.getClosedWindowCount() == 0)
  7871.     undoPopup.parentNode.setAttribute("disabled", true);
  7872.   else
  7873.     undoPopup.parentNode.removeAttribute("disabled");
  7874. }
  7875.  
  7876. /**
  7877.  * Populate when the history menu is opened
  7878.  */
  7879. HistoryMenu.populateUndoWindowSubmenu = function PHM_populateUndoWindowSubmenu() {
  7880.   let undoPopup = document.getElementById("historyUndoWindowPopup");
  7881.   let menuLabelString = gNavigatorBundle.getString("menuUndoCloseWindowLabel");
  7882.   let menuLabelStringSingleTab =
  7883.     gNavigatorBundle.getString("menuUndoCloseWindowSingleTabLabel");
  7884.  
  7885.   // remove existing menu items
  7886.   while (undoPopup.hasChildNodes())
  7887.     undoPopup.removeChild(undoPopup.firstChild);
  7888.  
  7889.   // no restorable windows, so make sure menu is disabled, and return
  7890.   if (this._ss.getClosedWindowCount() == 0) {
  7891.     undoPopup.parentNode.setAttribute("disabled", true);
  7892.     return;
  7893.   }
  7894.  
  7895.   // enable menu
  7896.   undoPopup.parentNode.removeAttribute("disabled");
  7897.  
  7898.   // populate menu
  7899.   let undoItems = JSON.parse(this._ss.getClosedWindowData());
  7900.   for (let i = 0; i < undoItems.length; i++) {
  7901.     let undoItem = undoItems[i];
  7902.     let otherTabsCount = undoItem.tabs.length - 1;
  7903.     let label = (otherTabsCount == 0) ? menuLabelStringSingleTab
  7904.                                       : PluralForm.get(otherTabsCount, menuLabelString);
  7905.     let menuLabel = label.replace("#1", undoItem.title)
  7906.                          .replace("#2", otherTabsCount);
  7907.     let m = document.createElement("menuitem");
  7908.     m.setAttribute("label", menuLabel);
  7909.     let selectedTab = undoItem.tabs[undoItem.selected - 1];
  7910.     if (selectedTab.attributes.image) {
  7911.       let iconURL = selectedTab.attributes.image;
  7912.       // don't initiate a connection just to fetch a favicon (see bug 467828)
  7913.       if (/^https?:/.test(iconURL))
  7914.         iconURL = "moz-anno:favicon:" + iconURL;
  7915.       m.setAttribute("image", iconURL);
  7916.     }
  7917.     m.setAttribute("class", "menuitem-iconic bookmark-item");
  7918.     m.setAttribute("oncommand", "undoCloseWindow(" + i + ");");
  7919.     if (i == 0)
  7920.       m.setAttribute("key", "key_undoCloseWindow");
  7921.     undoPopup.appendChild(m);
  7922.   }
  7923.  
  7924.   // "Open All in Windows"
  7925.   undoPopup.appendChild(document.createElement("menuseparator"));
  7926.   let m = undoPopup.appendChild(document.createElement("menuitem"));
  7927.   m.setAttribute("label", gNavigatorBundle.getString("menuRestoreAllWindows.label"));
  7928.   m.setAttribute("accesskey", gNavigatorBundle.getString("menuRestoreAllWindows.accesskey"));
  7929.   m.setAttribute("oncommand",
  7930.     "for (var i = 0; i < " + undoItems.length + "; i++) undoCloseWindow();");
  7931. }
  7932.  
  7933. /**
  7934.   * Re-open a closed tab and put it to the end of the tab strip. 
  7935.   * Used for a middle click.
  7936.   * @param aEvent
  7937.   *        The event when the user clicks the menu item
  7938.   */
  7939. function undoCloseMiddleClick(aEvent) {
  7940.   if (aEvent.button != 1)
  7941.     return;
  7942.  
  7943.   undoCloseTab(aEvent.originalTarget.value);
  7944.   gBrowser.moveTabToEnd();
  7945. }
  7946.  
  7947. /**
  7948.  * Re-open a closed tab.
  7949.  * @param aIndex
  7950.  *        The index of the tab (via nsSessionStore.getClosedTabData)
  7951.  * @returns a reference to the reopened tab.
  7952.  */
  7953. function undoCloseTab(aIndex) {
  7954.   // wallpaper patch to prevent an unnecessary blank tab (bug 343895)
  7955.   var blankTabToRemove = null;
  7956.   if (gBrowser.tabContainer.childNodes.length == 1 &&
  7957.       !gPrefService.getBoolPref("browser.tabs.autoHide") &&
  7958.       gBrowser.selectedBrowser.sessionHistory.count < 2 &&
  7959.       gBrowser.selectedBrowser.currentURI.spec == "about:blank" &&
  7960.       !gBrowser.selectedBrowser.contentDocument.body.hasChildNodes() &&
  7961.       !gBrowser.selectedTab.hasAttribute("busy"))
  7962.     blankTabToRemove = gBrowser.selectedTab;
  7963.  
  7964.   var tab = null;
  7965.   var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  7966.            getService(Ci.nsISessionStore);
  7967.   if (ss.getClosedTabCount(window) > (aIndex || 0)) {
  7968.     tab = ss.undoCloseTab(window, aIndex || 0);
  7969.     
  7970.     if (blankTabToRemove)
  7971.       gBrowser.removeTab(blankTabToRemove);
  7972.   }
  7973.   
  7974.   return tab;
  7975. }
  7976.  
  7977. /**
  7978.  * Re-open a closed window.
  7979.  * @param aIndex
  7980.  *        The index of the window (via nsSessionStore.getClosedWindowData)
  7981.  * @returns a reference to the reopened window.
  7982.  */
  7983. function undoCloseWindow(aIndex) {
  7984.   let ss = Cc["@mozilla.org/browser/sessionstore;1"].
  7985.            getService(Ci.nsISessionStore);
  7986.   let window = null;
  7987.   if (ss.getClosedWindowCount() > (aIndex || 0))
  7988.     window = ss.undoCloseWindow(aIndex || 0);
  7989.  
  7990.   return window;
  7991. }
  7992.  
  7993. /**
  7994.  * Format a URL
  7995.  * eg:
  7996.  * echo formatURL("http://%LOCALE%.amo.mozilla.org/%LOCALE%/%APP%/%VERSION%/");
  7997.  * > http://en-US.amo.mozilla.org/en-US/firefox/3.0a1/
  7998.  *
  7999.  * Currently supported built-ins are LOCALE, APP, and any value from nsIXULAppInfo, uppercased.
  8000.  */
  8001. function formatURL(aFormat, aIsPref) {
  8002.   var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].getService(Ci.nsIURLFormatter);
  8003.   return aIsPref ? formatter.formatURLPref(aFormat) : formatter.formatURL(aFormat);
  8004. }
  8005.  
  8006. /**
  8007.  * This also takes care of updating the command enabled-state when tabs are
  8008.  * created or removed.
  8009.  */
  8010. function BookmarkAllTabsHandler() {
  8011.   this._command = document.getElementById("Browser:BookmarkAllTabs");
  8012.   gBrowser.addEventListener("TabOpen", this, true);
  8013.   gBrowser.addEventListener("TabClose", this, true);
  8014.   this._updateCommandState();
  8015. }
  8016.  
  8017. BookmarkAllTabsHandler.prototype = {
  8018.   QueryInterface: function BATH_QueryInterface(aIID) {
  8019.     if (aIID.equals(Ci.nsIDOMEventListener) ||
  8020.         aIID.equals(Ci.nsISupports))
  8021.       return this;
  8022.  
  8023.     throw Cr.NS_NOINTERFACE;
  8024.   },
  8025.  
  8026.   _updateCommandState: function BATH__updateCommandState(aTabClose) {
  8027.     var numTabs = gBrowser.tabContainer.childNodes.length;
  8028.  
  8029.     // The TabClose event is fired before the tab is removed from the DOM
  8030.     if (aTabClose)
  8031.       numTabs--;
  8032.  
  8033.     if (numTabs > 1)
  8034.       this._command.removeAttribute("disabled");
  8035.     else
  8036.       this._command.setAttribute("disabled", "true");
  8037.   },
  8038.  
  8039.   doCommand: function BATH_doCommand() {
  8040.     PlacesCommandHook.bookmarkCurrentPages();
  8041.   },
  8042.  
  8043.   // nsIDOMEventListener
  8044.   handleEvent: function(aEvent) {
  8045.     this._updateCommandState(aEvent.type == "TabClose");
  8046.   }
  8047. };
  8048.  
  8049. /**
  8050.  * Utility object to handle manipulations of the identity indicators in the UI
  8051.  */
  8052. var gIdentityHandler = {
  8053.   // Mode strings used to control CSS display
  8054.   IDENTITY_MODE_IDENTIFIED       : "verifiedIdentity", // High-quality identity information
  8055.   IDENTITY_MODE_DOMAIN_VERIFIED  : "verifiedDomain",   // Minimal SSL CA-signed domain verification
  8056.   IDENTITY_MODE_UNKNOWN          : "unknownIdentity",  // No trusted identity information
  8057.  
  8058.   // Cache the most recent SSLStatus and Location seen in checkIdentity
  8059.   _lastStatus : null,
  8060.   _lastLocation : null,
  8061.  
  8062.   // smart getters
  8063.   get _stringBundle () {
  8064.     delete this._stringBundle;
  8065.     return this._stringBundle = document.getElementById("bundle_browser");
  8066.   },
  8067.   get _staticStrings () {
  8068.     delete this._staticStrings;
  8069.     this._staticStrings = {};
  8070.     this._staticStrings[this.IDENTITY_MODE_DOMAIN_VERIFIED] = {
  8071.       encryption_label: this._stringBundle.getString("identity.encrypted")
  8072.     };
  8073.     this._staticStrings[this.IDENTITY_MODE_IDENTIFIED] = {
  8074.       encryption_label: this._stringBundle.getString("identity.encrypted")
  8075.     };
  8076.     this._staticStrings[this.IDENTITY_MODE_UNKNOWN] = {
  8077.       encryption_label: this._stringBundle.getString("identity.unencrypted")
  8078.     };
  8079.     return this._staticStrings;
  8080.   },
  8081.   get _identityPopup () {
  8082.     delete this._identityPopup;
  8083.     return this._identityPopup = document.getElementById("identity-popup");
  8084.   },
  8085.   get _identityBox () {
  8086.     delete this._identityBox;
  8087.     return this._identityBox = document.getElementById("identity-box");
  8088.   },
  8089.   get _identityPopupContentBox () {
  8090.     delete this._identityPopupContentBox;
  8091.     return this._identityPopupContentBox =
  8092.       document.getElementById("identity-popup-content-box");
  8093.   },
  8094.   get _identityPopupContentHost () {
  8095.     delete this._identityPopupContentHost;
  8096.     return this._identityPopupContentHost =
  8097.       document.getElementById("identity-popup-content-host");
  8098.   },
  8099.   get _identityPopupContentOwner () {
  8100.     delete this._identityPopupContentOwner;
  8101.     return this._identityPopupContentOwner =
  8102.       document.getElementById("identity-popup-content-owner");
  8103.   },
  8104.   get _identityPopupContentSupp () {
  8105.     delete this._identityPopupContentSupp;
  8106.     return this._identityPopupContentSupp =
  8107.       document.getElementById("identity-popup-content-supplemental");
  8108.   },
  8109.   get _identityPopupContentVerif () {
  8110.     delete this._identityPopupContentVerif;
  8111.     return this._identityPopupContentVerif =
  8112.       document.getElementById("identity-popup-content-verifier");
  8113.   },
  8114.   get _identityPopupEncLabel () {
  8115.     delete this._identityPopupEncLabel;
  8116.     return this._identityPopupEncLabel =
  8117.       document.getElementById("identity-popup-encryption-label");
  8118.   },
  8119.   get _identityIconLabel () {
  8120.     delete this._identityIconLabel;
  8121.     return this._identityIconLabel = document.getElementById("identity-icon-label");
  8122.   },
  8123.  
  8124.   /**
  8125.    * Rebuild cache of the elements that may or may not exist depending
  8126.    * on whether there's a location bar.
  8127.    */
  8128.   _cacheElements : function() {
  8129.     delete this._identityBox;
  8130.     delete this._identityIconLabel;
  8131.     this._identityBox = document.getElementById("identity-box");
  8132.     this._identityIconLabel = document.getElementById("identity-icon-label");
  8133.   },
  8134.  
  8135.   /**
  8136.    * Handler for mouseclicks on the "More Information" button in the
  8137.    * "identity-popup" panel.
  8138.    */
  8139.   handleMoreInfoClick : function(event) {
  8140.     displaySecurityInfo();
  8141.     event.stopPropagation();
  8142.   },
  8143.   
  8144.   /**
  8145.    * Helper to parse out the important parts of _lastStatus (of the SSL cert in
  8146.    * particular) for use in constructing identity UI strings
  8147.   */
  8148.   getIdentityData : function() {
  8149.     var result = {};
  8150.     var status = this._lastStatus.QueryInterface(Components.interfaces.nsISSLStatus);
  8151.     var cert = status.serverCert;
  8152.     
  8153.     // Human readable name of Subject
  8154.     result.subjectOrg = cert.organization;
  8155.     
  8156.     // SubjectName fields, broken up for individual access
  8157.     if (cert.subjectName) {
  8158.       result.subjectNameFields = {};
  8159.       cert.subjectName.split(",").forEach(function(v) {
  8160.         var field = v.split("=");
  8161.         this[field[0]] = field[1];
  8162.       }, result.subjectNameFields);
  8163.       
  8164.       // Call out city, state, and country specifically
  8165.       result.city = result.subjectNameFields.L;
  8166.       result.state = result.subjectNameFields.ST;
  8167.       result.country = result.subjectNameFields.C;
  8168.     }
  8169.     
  8170.     // Human readable name of Certificate Authority
  8171.     result.caOrg =  cert.issuerOrganization || cert.issuerCommonName;
  8172.     result.cert = cert;
  8173.     
  8174.     return result;
  8175.   },
  8176.   
  8177.   /**
  8178.    * Determine the identity of the page being displayed by examining its SSL cert
  8179.    * (if available) and, if necessary, update the UI to reflect this.  Intended to
  8180.    * be called by onSecurityChange
  8181.    * 
  8182.    * @param PRUint32 state
  8183.    * @param JS Object location that mirrors an nsLocation (i.e. has .host and
  8184.    *                           .hostname and .port)
  8185.    */
  8186.   checkIdentity : function(state, location) {
  8187.     var currentStatus = gBrowser.securityUI
  8188.                                 .QueryInterface(Components.interfaces.nsISSLStatusProvider)
  8189.                                 .SSLStatus;
  8190.     this._lastStatus = currentStatus;
  8191.     this._lastLocation = location;
  8192.     
  8193.     if (state & Components.interfaces.nsIWebProgressListener.STATE_IDENTITY_EV_TOPLEVEL)
  8194.       this.setMode(this.IDENTITY_MODE_IDENTIFIED);
  8195.     else if (state & Components.interfaces.nsIWebProgressListener.STATE_SECURE_HIGH)
  8196.       this.setMode(this.IDENTITY_MODE_DOMAIN_VERIFIED);
  8197.     else
  8198.       this.setMode(this.IDENTITY_MODE_UNKNOWN);
  8199.   },
  8200.   
  8201.   /**
  8202.    * Return the eTLD+1 version of the current hostname
  8203.    */
  8204.   getEffectiveHost : function() {
  8205.     // Cache the eTLDService if this is our first time through
  8206.     if (!this._eTLDService)
  8207.       this._eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"]
  8208.                          .getService(Ci.nsIEffectiveTLDService);
  8209.     try {
  8210.       return this._eTLDService.getBaseDomainFromHost(this._lastLocation.hostname);
  8211.     } catch (e) {
  8212.       // If something goes wrong (e.g. hostname is an IP address) just fail back
  8213.       // to the full domain.
  8214.       return this._lastLocation.hostname;
  8215.     }
  8216.   },
  8217.   
  8218.   /**
  8219.    * Update the UI to reflect the specified mode, which should be one of the
  8220.    * IDENTITY_MODE_* constants.
  8221.    */
  8222.   setMode : function(newMode) {
  8223.     if (!this._identityBox) {
  8224.       // No identity box means the identity box is not visible, in which
  8225.       // case there's nothing to do.
  8226.       return;
  8227.     }
  8228.  
  8229.     this._identityBox.className = newMode;
  8230.     this.setIdentityMessages(newMode);
  8231.     
  8232.     // Update the popup too, if it's open
  8233.     if (this._identityPopup.state == "open")
  8234.       this.setPopupMessages(newMode);
  8235.   },
  8236.   
  8237.   /**
  8238.    * Set up the messages for the primary identity UI based on the specified mode,
  8239.    * and the details of the SSL cert, where applicable
  8240.    *
  8241.    * @param newMode The newly set identity mode.  Should be one of the IDENTITY_MODE_* constants.
  8242.    */
  8243.   setIdentityMessages : function(newMode) {
  8244.     if (newMode == this.IDENTITY_MODE_DOMAIN_VERIFIED) {
  8245.       var iData = this.getIdentityData();     
  8246.       
  8247.       // It would be sort of nice to use the CN= field in the cert, since that's
  8248.       // typically what we want here, but thanks to x509 certs being extensible,
  8249.       // it's not the only place you have to check, there can be more than one domain,
  8250.       // et cetera, ad nauseum.  We know the cert is valid for location.host, so
  8251.       // let's just use that. Check the pref to determine how much of the verified
  8252.       // hostname to show
  8253.       var icon_label = "";
  8254.       switch (gPrefService.getIntPref("browser.identity.ssl_domain_display")) {
  8255.         case 2 : // Show full domain
  8256.           icon_label = this._lastLocation.hostname;
  8257.           break;
  8258.         case 1 : // Show eTLD.
  8259.           icon_label = this.getEffectiveHost();
  8260.       }
  8261.       
  8262.       // We need a port number for all lookups.  If one hasn't been specified, use
  8263.       // the https default
  8264.       var lookupHost = this._lastLocation.host;
  8265.       if (lookupHost.indexOf(':') < 0)
  8266.         lookupHost += ":443";
  8267.  
  8268.       // Cache the override service the first time we need to check it
  8269.       if (!this._overrideService)
  8270.         this._overrideService = Components.classes["@mozilla.org/security/certoverride;1"]
  8271.                                           .getService(Components.interfaces.nsICertOverrideService);
  8272.  
  8273.       // Verifier is either the CA Org, for a normal cert, or a special string
  8274.       // for certs that are trusted because of a security exception.
  8275.       var tooltip = this._stringBundle.getFormattedString("identity.identified.verifier",
  8276.                                                           [iData.caOrg]);
  8277.       
  8278.       // Check whether this site is a security exception. XPConnect does the right
  8279.       // thing here in terms of converting _lastLocation.port from string to int, but
  8280.       // the overrideService doesn't like undefined ports, so make sure we have
  8281.       // something in the default case (bug 432241).
  8282.       if (this._overrideService.hasMatchingOverride(this._lastLocation.hostname, 
  8283.                                                     (this._lastLocation.port || 443),
  8284.                                                     iData.cert, {}, {}))
  8285.         tooltip = this._stringBundle.getString("identity.identified.verified_by_you");
  8286.     }
  8287.     else if (newMode == this.IDENTITY_MODE_IDENTIFIED) {
  8288.       // If it's identified, then we can populate the dialog with credentials
  8289.       iData = this.getIdentityData();  
  8290.       tooltip = this._stringBundle.getFormattedString("identity.identified.verifier",
  8291.                                                       [iData.caOrg]);
  8292.       if (iData.country)
  8293.         icon_label = this._stringBundle.getFormattedString("identity.identified.title_with_country",
  8294.                                                            [iData.subjectOrg, iData.country]);
  8295.       else
  8296.         icon_label = iData.subjectOrg;
  8297.     }
  8298.     else {
  8299.       tooltip = this._stringBundle.getString("identity.unknown.tooltip");
  8300.       icon_label = "";
  8301.     }
  8302.     
  8303.     // Push the appropriate strings out to the UI
  8304.     this._identityBox.tooltipText = tooltip;
  8305.     this._identityIconLabel.value = icon_label;
  8306.   },
  8307.   
  8308.   /**
  8309.    * Set up the title and content messages for the identity message popup,
  8310.    * based on the specified mode, and the details of the SSL cert, where
  8311.    * applicable
  8312.    *
  8313.    * @param newMode The newly set identity mode.  Should be one of the IDENTITY_MODE_* constants.
  8314.    */
  8315.   setPopupMessages : function(newMode) {
  8316.       
  8317.     this._identityPopup.className = newMode;
  8318.     this._identityPopupContentBox.className = newMode;
  8319.     
  8320.     // Set the static strings up front
  8321.     this._identityPopupEncLabel.textContent = this._staticStrings[newMode].encryption_label;
  8322.     
  8323.     // Initialize the optional strings to empty values
  8324.     var supplemental = "";
  8325.     var verifier = "";
  8326.     
  8327.     if (newMode == this.IDENTITY_MODE_DOMAIN_VERIFIED) {
  8328.       var iData = this.getIdentityData();
  8329.       var host = this.getEffectiveHost();
  8330.       var owner = this._stringBundle.getString("identity.ownerUnknown2");
  8331.       verifier = this._identityBox.tooltipText;
  8332.       supplemental = "";
  8333.     }
  8334.     else if (newMode == this.IDENTITY_MODE_IDENTIFIED) {
  8335.       // If it's identified, then we can populate the dialog with credentials
  8336.       iData = this.getIdentityData();
  8337.       host = this.getEffectiveHost();
  8338.       owner = iData.subjectOrg; 
  8339.       verifier = this._identityBox.tooltipText;
  8340.  
  8341.       // Build an appropriate supplemental block out of whatever location data we have
  8342.       if (iData.city)
  8343.         supplemental += iData.city + "\n";        
  8344.       if (iData.state && iData.country)
  8345.         supplemental += this._stringBundle.getFormattedString("identity.identified.state_and_country",
  8346.                                                               [iData.state, iData.country]);
  8347.       else if (iData.state) // State only
  8348.         supplemental += iData.state;
  8349.       else if (iData.country) // Country only
  8350.         supplemental += iData.country;
  8351.     }
  8352.     else {
  8353.       // These strings will be hidden in CSS anyhow
  8354.       host = "";
  8355.       owner = "";
  8356.     }
  8357.     
  8358.     // Push the appropriate strings out to the UI
  8359.     this._identityPopupContentHost.textContent = host;
  8360.     this._identityPopupContentOwner.textContent = owner;
  8361.     this._identityPopupContentSupp.textContent = supplemental;
  8362.     this._identityPopupContentVerif.textContent = verifier;
  8363.   },
  8364.  
  8365.   hideIdentityPopup : function() {
  8366.     this._identityPopup.hidePopup();
  8367.   },
  8368.  
  8369.   /**
  8370.    * Click handler for the identity-box element in primary chrome.  
  8371.    */
  8372.   handleIdentityButtonEvent : function(event) {
  8373.   
  8374.     event.stopPropagation();
  8375.  
  8376.     if ((event.type == "click" && event.button != 0) ||
  8377.         (event.type == "keypress" && event.charCode != KeyEvent.DOM_VK_SPACE &&
  8378.          event.keyCode != KeyEvent.DOM_VK_RETURN))
  8379.       return; // Left click, space or enter only
  8380.  
  8381.     // Revert the contents of the location bar, see bug 406779
  8382.     gURLBar.handleRevert();
  8383.  
  8384.     // Make sure that the display:none style we set in xul is removed now that
  8385.     // the popup is actually needed
  8386.     this._identityPopup.hidden = false;
  8387.     
  8388.     // Tell the popup to consume dismiss clicks, to avoid bug 395314
  8389.     this._identityPopup.popupBoxObject
  8390.         .setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  8391.     
  8392.     // Update the popup strings
  8393.     this.setPopupMessages(this._identityBox.className);
  8394.     
  8395.     // Make sure the identity popup hangs toward the middle of the location bar
  8396.     // in RTL builds
  8397.     var position = 'after_start';
  8398.     if (gURLBar.getAttribute("chromedir") == "rtl")
  8399.       position = 'after_end';
  8400.  
  8401.     // Add the "open" attribute to the identity box for styling
  8402.     this._identityBox.setAttribute("open", "true");
  8403.     var self = this;
  8404.     this._identityPopup.addEventListener("popuphidden", function (e) {
  8405.       e.currentTarget.removeEventListener("popuphidden", arguments.callee, false);
  8406.       self._identityBox.removeAttribute("open");
  8407.     }, false);
  8408.  
  8409.     // Now open the popup, anchored off the primary chrome element
  8410.     this._identityPopup.openPopup(this._identityBox, position);
  8411.   }
  8412. };
  8413.  
  8414. let DownloadMonitorPanel = {
  8415.   //////////////////////////////////////////////////////////////////////////////
  8416.   //// DownloadMonitorPanel Member Variables
  8417.  
  8418.   _panel: null,
  8419.   _activeStr: null,
  8420.   _pausedStr: null,
  8421.   _lastTime: Infinity,
  8422.   _listening: false,
  8423.  
  8424.   //////////////////////////////////////////////////////////////////////////////
  8425.   //// DownloadMonitorPanel Public Methods
  8426.  
  8427.   /**
  8428.    * Initialize the status panel and member variables
  8429.    */
  8430.   init: function DMP_init() {
  8431.     // Load the modules to help display strings
  8432.     Cu.import("resource://gre/modules/DownloadUtils.jsm");
  8433.  
  8434.     // Initialize "private" member variables
  8435.     this._panel = document.getElementById("download-monitor");
  8436.  
  8437.     // Cache the status strings
  8438.     let (bundle = document.getElementById("bundle_browser")) {
  8439.       this._activeStr = bundle.getString("activeDownloads");
  8440.       this._pausedStr = bundle.getString("pausedDownloads");
  8441.     }
  8442.  
  8443.     gDownloadMgr.addListener(this);
  8444.     this._listening = true;
  8445.  
  8446.     this.updateStatus();
  8447.   },
  8448.  
  8449.   uninit: function DMP_uninit() {
  8450.     if (this._listening)
  8451.       gDownloadMgr.removeListener(this);
  8452.   },
  8453.  
  8454.   /**
  8455.    * Update status based on the number of active and paused downloads
  8456.    */
  8457.   updateStatus: function DMP_updateStatus() {
  8458.     let numActive = gDownloadMgr.activeDownloadCount;
  8459.  
  8460.     // Hide the panel and reset the "last time" if there's no downloads
  8461.     if (numActive == 0) {
  8462.       this._panel.hidden = true;
  8463.       this._lastTime = Infinity;
  8464.  
  8465.       return;
  8466.     }
  8467.   
  8468.     // Find the download with the longest remaining time
  8469.     let numPaused = 0;
  8470.     let maxTime = -Infinity;
  8471.     let dls = gDownloadMgr.activeDownloads;
  8472.     while (dls.hasMoreElements()) {
  8473.       let dl = dls.getNext().QueryInterface(Ci.nsIDownload);
  8474.       if (dl.state == gDownloadMgr.DOWNLOAD_DOWNLOADING) {
  8475.         // Figure out if this download takes longer
  8476.         if (dl.speed > 0 && dl.size > 0)
  8477.           maxTime = Math.max(maxTime, (dl.size - dl.amountTransferred) / dl.speed);
  8478.         else
  8479.           maxTime = -1;
  8480.       }
  8481.       else if (dl.state == gDownloadMgr.DOWNLOAD_PAUSED)
  8482.         numPaused++;
  8483.     }
  8484.  
  8485.     // Get the remaining time string and last sec for time estimation
  8486.     let timeLeft;
  8487.     [timeLeft, this._lastTime] = DownloadUtils.getTimeLeft(maxTime, this._lastTime);
  8488.  
  8489.     // Figure out how many downloads are currently downloading
  8490.     let numDls = numActive - numPaused;
  8491.     let status = this._activeStr;
  8492.  
  8493.     // If all downloads are paused, show the paused message instead
  8494.     if (numDls == 0) {
  8495.       numDls = numPaused;
  8496.       status = this._pausedStr;
  8497.     }
  8498.  
  8499.     // Get the correct plural form and insert the number of downloads and time
  8500.     // left message if necessary
  8501.     status = PluralForm.get(numDls, status);
  8502.     status = status.replace("#1", numDls);
  8503.     status = status.replace("#2", timeLeft);
  8504.  
  8505.     // Update the panel and show it
  8506.     this._panel.label = status;
  8507.     this._panel.hidden = false;
  8508.   },
  8509.  
  8510.   //////////////////////////////////////////////////////////////////////////////
  8511.   //// nsIDownloadProgressListener
  8512.  
  8513.   /**
  8514.    * Update status for download progress changes
  8515.    */
  8516.   onProgressChange: function() {
  8517.     this.updateStatus();
  8518.   },
  8519.  
  8520.   /**
  8521.    * Update status for download state changes
  8522.    */
  8523.   onDownloadStateChange: function() {
  8524.     this.updateStatus();
  8525.   },
  8526.  
  8527.   onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus, aDownload) {
  8528.   },
  8529.  
  8530.   onSecurityChange: function(aWebProgress, aRequest, aState, aDownload) {
  8531.   },
  8532.  
  8533.   //////////////////////////////////////////////////////////////////////////////
  8534.   //// nsISupports
  8535.  
  8536.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIDownloadProgressListener]),
  8537. };
  8538.  
  8539. function getNotificationBox(aWindow) {
  8540.   var foundBrowser = gBrowser.getBrowserForDocument(aWindow.document);
  8541.   if (foundBrowser)
  8542.     return gBrowser.getNotificationBox(foundBrowser)
  8543.   return null;
  8544. };
  8545.  
  8546. /* DEPRECATED */
  8547. function getBrowser() gBrowser;
  8548. function getNavToolbox() gNavToolbox;
  8549.  
  8550. let gPrivateBrowsingUI = {
  8551.   _observerService: null,
  8552.   _privateBrowsingService: null,
  8553.   _privateBrowsingAutoStarted: false,
  8554.  
  8555.   init: function PBUI_init() {
  8556.     this._observerService = Cc["@mozilla.org/observer-service;1"].
  8557.                             getService(Ci.nsIObserverService);
  8558.     this._observerService.addObserver(this, "private-browsing", false);
  8559.  
  8560.     this._privateBrowsingService = Cc["@mozilla.org/privatebrowsing;1"].
  8561.                                    getService(Ci.nsIPrivateBrowsingService);
  8562.  
  8563.     if (this.privateBrowsingEnabled)
  8564.       this.onEnterPrivateBrowsing();
  8565.   },
  8566.  
  8567.   uninit: function PBUI_unint() {
  8568.     this._observerService.removeObserver(this, "private-browsing");
  8569.   },
  8570.  
  8571.   observe: function PBUI_observe(aSubject, aTopic, aData) {
  8572.     if (aTopic == "private-browsing") {
  8573.       if (aData == "enter")
  8574.         this.onEnterPrivateBrowsing();
  8575.       else if (aData == "exit")
  8576.         this.onExitPrivateBrowsing();
  8577.     }
  8578.   },
  8579.  
  8580.   _shouldEnter: function PBUI__shouldEnter() {
  8581.     try {
  8582.       // Never prompt if the session is not going to be closed, or if user has
  8583.       // already requested not to be prompted.
  8584.       if (gPrefService.getBoolPref("browser.privatebrowsing.dont_prompt_on_enter") ||
  8585.           gPrefService.getBoolPref("browser.privatebrowsing.keep_current_session"))
  8586.         return true;
  8587.     }
  8588.     catch (ex) { }
  8589.  
  8590.     var bundleService = Cc["@mozilla.org/intl/stringbundle;1"].
  8591.                         getService(Ci.nsIStringBundleService);
  8592.     var pbBundle = bundleService.createBundle("chrome://browser/locale/browser.properties");
  8593.     var brandBundle = bundleService.createBundle("chrome://branding/locale/brand.properties");
  8594.  
  8595.     var appName = brandBundle.GetStringFromName("brandShortName");
  8596. //@line 7061 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  8597.     var dialogTitle = pbBundle.GetStringFromName("privateBrowsingDialogTitle");
  8598.     var header = pbBundle.GetStringFromName("privateBrowsingMessageHeader") + "\n\n";
  8599. //@line 7064 "e:\builds\moz2_slave\win32_build\build\browser\base\content\browser.js"
  8600.     var message = pbBundle.formatStringFromName("privateBrowsingMessage", [appName], 1);
  8601.  
  8602.     var promptService = Cc["@mozilla.org/embedcomp/prompt-service;1"].
  8603.                         getService(Ci.nsIPromptService);
  8604.  
  8605.     var flags = promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
  8606.                 promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
  8607.                 promptService.BUTTON_POS_0_DEFAULT;
  8608.  
  8609.     var neverAsk = {value:false};
  8610.     var button0Title = pbBundle.GetStringFromName("privateBrowsingYesTitle");
  8611.     var button1Title = pbBundle.GetStringFromName("privateBrowsingNoTitle");
  8612.     var neverAskText = pbBundle.GetStringFromName("privateBrowsingNeverAsk");
  8613.  
  8614.     var result;
  8615.     var choice = promptService.confirmEx(null, dialogTitle, header + message,
  8616.                                flags, button0Title, button1Title, null,
  8617.                                neverAskText, neverAsk);
  8618.  
  8619.     switch (choice) {
  8620.     case 0: // Start Private Browsing
  8621.       result = true;
  8622.       if (neverAsk.value)
  8623.         gPrefService.setBoolPref("browser.privatebrowsing.dont_prompt_on_enter", true);
  8624.       break;
  8625.     case 1: // Keep
  8626.       result = false;
  8627.       break;
  8628.     }
  8629.  
  8630.     return result;
  8631.   },
  8632.  
  8633.   onEnterPrivateBrowsing: function PBUI_onEnterPrivateBrowsing() {
  8634.     this._setPBMenuTitle("stop");
  8635.  
  8636.     document.getElementById("menu_import").setAttribute("disabled", "true");
  8637.     
  8638.     // Disable the Clear Recent History... menu item when in PB mode
  8639.     // 1.9.1 branch only (bug 480260)
  8640.     document.getElementById("Tools:Sanitize").setAttribute("disabled", "true");
  8641.  
  8642.     this._privateBrowsingAutoStarted = this._privateBrowsingService.autoStarted;
  8643.  
  8644.     if (this._privateBrowsingAutoStarted) {
  8645.       // Disable the menu item in auto-start mode
  8646.       document.getElementById("privateBrowsingItem")
  8647.               .setAttribute("disabled", "true");
  8648.       document.getElementById("Tools:PrivateBrowsing")
  8649.               .setAttribute("disabled", "true");
  8650.     }
  8651.     else if (window.location.href == getBrowserURL()) {
  8652.       // Adjust the window's title
  8653.       let docElement = document.documentElement;
  8654.       docElement.setAttribute("title",
  8655.         docElement.getAttribute("title_privatebrowsing"));
  8656.       docElement.setAttribute("titlemodifier",
  8657.         docElement.getAttribute("titlemodifier_privatebrowsing"));
  8658.       docElement.setAttribute("browsingmode", "private");
  8659.     }
  8660.   },
  8661.  
  8662.   onExitPrivateBrowsing: function PBUI_onExitPrivateBrowsing() {
  8663.     if (BrowserSearch.searchBar)
  8664.       BrowserSearch.searchBar.textbox.reset();
  8665.  
  8666.     document.getElementById("menu_import").removeAttribute("disabled");
  8667.  
  8668.     // Re-enable the Clear Recent History... menu item on exit of PB mode
  8669.     // 1.9.1 branch only (bug 480260)
  8670.     document.getElementById("Tools:Sanitize").removeAttribute("disabled");
  8671.  
  8672.     if (gFindBar)
  8673.       gFindBar.getElement("findbar-textbox").reset();
  8674.  
  8675.     this._setPBMenuTitle("start");
  8676.  
  8677.     if (window.location.href == getBrowserURL()) {
  8678.       // Adjust the window's title
  8679.       let docElement = document.documentElement;
  8680.       docElement.setAttribute("title",
  8681.         docElement.getAttribute("title_normal"));
  8682.       docElement.setAttribute("titlemodifier",
  8683.         docElement.getAttribute("titlemodifier_normal"));
  8684.       docElement.setAttribute("browsingmode", "normal");
  8685.     }
  8686.  
  8687.     // Enable the menu item in after exiting the auto-start mode
  8688.     document.getElementById("privateBrowsingItem")
  8689.             .removeAttribute("disabled");
  8690.     document.getElementById("Tools:PrivateBrowsing")
  8691.             .removeAttribute("disabled");
  8692.  
  8693.     this._privateBrowsingAutoStarted = false;
  8694.   },
  8695.  
  8696.   _setPBMenuTitle: function PBUI__setPBMenuTitle(aMode) {
  8697.     let pbMenuItem = document.getElementById("privateBrowsingItem");
  8698.     pbMenuItem.setAttribute("label", pbMenuItem.getAttribute(aMode + "label"));
  8699.     pbMenuItem.setAttribute("accesskey", pbMenuItem.getAttribute(aMode + "accesskey"));
  8700.   },
  8701.  
  8702.   toggleMode: function PBUI_toggleMode() {
  8703.     // prompt the users on entering the private mode, if needed
  8704.     if (!this.privateBrowsingEnabled)
  8705.       if (!this._shouldEnter())
  8706.         return;
  8707.  
  8708.     this._privateBrowsingService.privateBrowsingEnabled =
  8709.       !this.privateBrowsingEnabled;
  8710.   },
  8711.  
  8712.   get privateBrowsingEnabled PBUI_get_privateBrowsingEnabled() {
  8713.     return this._privateBrowsingService.privateBrowsingEnabled;
  8714.   }
  8715. };
  8716.  
  8717. let gURLBarEmptyText = {
  8718.   domain: "browser.urlbar.",
  8719.  
  8720.   observe: function UBET_observe(aSubject, aTopic, aPrefName) {
  8721.     if (aTopic == "nsPref:changed") {
  8722.       switch (aPrefName) {
  8723.       case "browser.urlbar.autocomplete.enabled":
  8724.       case "browser.urlbar.default.behavior":
  8725.         gURLBar.emptyText = this.value;
  8726.         break;
  8727.       }
  8728.     }
  8729.   },
  8730.  
  8731.   get value UBET_get_value() {
  8732.     let type = "none";
  8733.     if (gPrefService.getBoolPref("browser.urlbar.autocomplete.enabled")) {
  8734.       // Bottom 2 bits of default.behavior specify history/bookmark
  8735.       switch (gPrefService.getIntPref("browser.urlbar.default.behavior") & 3) {
  8736.       case 0:
  8737.         type = "bookmarkhistory";
  8738.         break;
  8739.       case 1:
  8740.         type = "history";
  8741.         break;
  8742.       case 2:
  8743.         type = "bookmark";
  8744.         break;
  8745.       }
  8746.     }
  8747.     return gURLBar.getAttribute(type + "emptytext");
  8748.   }
  8749. };
  8750.